public static Matcher<String> withinSecondsAfter(Seconds seconds, DateTime after) { return new TypeSafeMatcher<String>() { @Override public void describeTo(Description description) { description.appendText(String.format( "a date time within %s seconds after %s", seconds.getSeconds(), after.toString())); } @Override protected boolean matchesSafely(String textRepresentation) { //response representation might vary from request representation DateTime actual = DateTime.parse(textRepresentation); return actual.isAfter(after) && Seconds.secondsBetween(after, actual).isLessThan(seconds); } }; }
private static void sendResponse( Channel channel, SocketAddress remoteAddress, ChannelBuffer id, int index, int report) { if (channel != null) { ChannelBuffer response = ChannelBuffers.dynamicBuffer(); response.writeBytes("SM".getBytes(StandardCharsets.US_ASCII)); response.writeByte(3); // protocol version response.writeByte(MSG_DATE_RECORD_ACK); response.writeBytes(id); response.writeInt(Seconds.secondsBetween( new DateTime(2000, 1, 1, 0, 0, DateTimeZone.UTC), new DateTime(DateTimeZone.UTC)).getSeconds()); response.writeByte(index); response.writeByte(report - 0x200); short checksum = (short) 0xF5A0; for (int i = 0; i < response.readableBytes(); i += 2) { checksum ^= ChannelBuffers.swapShort(response.getShort(i)); } response.writeShort(checksum); channel.write(response, remoteAddress); } }
public static void mergeFile() { String rootPath = "D:/bdsoft/vko/tianli_act_code"; String destPath = rootPath + "/all_code.txt"; File rootDir = new File(rootPath); if (rootDir.exists()) { File[] fileArr = rootDir.listFiles(); DateTime start = new DateTime(); System.out.println("开始:" + start.toLocalDateTime()); for (File file : fileArr) { readFrom(destPath, file); } DateTime end = new DateTime(); System.out.println("结束:" + end.toLocalDateTime()); String msg = String.format("文件合并完毕,耗时:%s分 %s秒", (Minutes.minutesBetween(start, end).getMinutes() % 60), (Seconds.secondsBetween(start, end).getSeconds() % 3600)); System.out.println(msg); } }
private int computeTimeModeAndDiff(DateTime dmin, DateTime dmax) { int diffDay = Days.daysBetween(dmin, dmax).getDays(); int diffHou = Hours.hoursBetween(dmin, dmax).getHours(); int diffMin = Minutes.minutesBetween(dmin, dmax).getMinutes(); int diffSec = Seconds.secondsBetween(dmin, dmax).getSeconds(); int diff = diffMin; guessTimeMode(diffDay, diffHou, diffMin, diffSec); if (TimeMode.DAY.equals(timeMode)) { diff = diffDay; } else if (TimeMode.HOUR.equals(timeMode)) { diff = diffHou; } else if (TimeMode.MINUTE.equals(timeMode)) { diff = diffMin; } else if (TimeMode.SECOND.equals(timeMode)) { diff = diffSec; } //consoleDiffs(diffDay, diffHou, diffMin, diffSec, diff); return diff; }
@RequestMapping("/poll") @ResponseBody public boolean pollIfLimitReached(@RequestAttribute User loggedUser) { if (loggedUser == null) { return false; } ActivitySession session = map.get(loggedUser.getId()); // no atomicity required, hence getting & putting sequentially if (session == null) { session = new ActivitySession(); session.setStart(new DateTime()); map.put(loggedUser.getId(), session); } // warn the user only once per session if (loggedUser.getProfile().isWarnOnMinutesPerDayLimit() && !session.isUserWarned()) { // the time today = the time save in the DB + the time of the current session so far int onlineSecondsToday = loggedUser.getOnlineSecondsToday() + Seconds.secondsBetween(session.getStart(), new DateTime()).getSeconds(); if (loggedUser.getProfile().getMinutesOnlinePerDay() * 60 < onlineSecondsToday) { session.setUserWarned(true); return true; } } return false; }
@Override @SqlTransactional public void onExpiry(String userId, ActivitySession session) { User user = getDao().getById(User.class, userId); logger.debug("Expiring activity session of user: " + user); session.setUser(user); session.setEnd(new DateTime()); session.setSeconds(Seconds.secondsBetween(session.getStart(), session.getEnd()).getSeconds()); save(session); if (user.getProfile().isWarnOnMinutesPerDayLimit()) { int secondsToday = user.getOnlineSecondsToday(); if (shouldResetOnlineSecondsToday(user)) { secondsToday = 0; } secondsToday += session.getSeconds(); user.setOnlineSecondsToday(secondsToday); } }
private static String dateToAge(String createdAt, DateTime now) { if (createdAt == null) { return ""; } DateTimeFormatter dtf = DateTimeFormat.forPattern(DATE_TIME_FORMAT); try { DateTime created = dtf.parseDateTime(createdAt); if (Seconds.secondsBetween(created, now).getSeconds() < 60) { return Seconds.secondsBetween(created, now).getSeconds() + "s"; } else if (Minutes.minutesBetween(created, now).getMinutes() < 60) { return Minutes.minutesBetween(created, now).getMinutes() + "m"; } else if (Hours.hoursBetween(created, now).getHours() < 24) { return Hours.hoursBetween(created, now).getHours() + "h"; } else { return Days.daysBetween(created, now).getDays() + "d"; } } catch (IllegalArgumentException e) { return ""; } }
@Override public Object create(Object request, SpecimenContext context) { if (!(request instanceof SpecimenType)) { return new NoSpecimen(); } SpecimenType type = (SpecimenType) request; if (!BaseSingleFieldPeriod.class.isAssignableFrom(type.getRawType())) { return new NoSpecimen(); } Duration duration = (Duration) context.resolve(Duration.class); if (type.equals(Seconds.class)) return Seconds.seconds(Math.max(1, (int) duration.getStandardSeconds())); if (type.equals(Minutes.class)) return Minutes.minutes(Math.max(1, (int) duration.getStandardMinutes())); if (type.equals(Hours.class)) return Hours.hours(Math.max(1, (int) duration.getStandardHours())); if (type.equals(Days.class)) return Days.days(Math.max(1, (int) duration.getStandardDays())); if (type.equals(Weeks.class)) return Weeks.weeks(Math.max(1, (int) duration.getStandardDays() / 7)); if (type.equals(Months.class)) return Months.months(Math.max(1, (int) duration.getStandardDays() / 30)); if (type.equals(Years.class)) return Years.years(Math.max(1, (int) duration.getStandardDays() / 365)); return new NoSpecimen(); }
/** * Validate an access_token. * The Oauth2 specification does not specify how this should be done. Do similar to what Google does * * @param access_token access token to validate. Be careful about using url safe tokens or use url encoding. * @return http 200 if success and some basic info about the access_token */ @GET @Path("tokeninfo") public Response validate(@QueryParam("access_token") String access_token) { checkNotNull(access_token); DConnection connection = connectionDao.findByAccessToken(access_token); LOGGER.debug("Connection {}", connection); if (null == connection || hasAccessTokenExpired(connection)) { throw new BadRequestRestException("Invalid access_token"); } return Response.ok(ImmutableMap.builder() .put("user_id", connection.getUserId()) .put("expires_in", Seconds.secondsBetween(DateTime.now(), new DateTime(connection.getExpireTime())).getSeconds()) .build()) .build(); }
@Test public void difference_between_two_dates_joda () { DateTime sinceGraduation = new DateTime(1984, 6, 4, 0, 0, GregorianChronology.getInstance()); DateTime currentDate = new DateTime(); //current date Days diffInDays = Days.daysBetween(sinceGraduation, currentDate); Hours diffInHours = Hours.hoursBetween(sinceGraduation, currentDate); Minutes diffInMinutes = Minutes.minutesBetween(sinceGraduation, currentDate); Seconds seconds = Seconds.secondsBetween(sinceGraduation, currentDate); logger.info(diffInDays.getDays()); logger.info(diffInHours.getHours()); logger.info(diffInMinutes.getMinutes()); logger.info(seconds.getSeconds()); assertTrue(diffInDays.getDays() >= 10697); assertTrue(diffInHours.getHours() >= 256747); assertTrue(diffInMinutes.getMinutes() >= 15404876); assertTrue(seconds.getSeconds() >= 924292577); }
private Map<String, Object> buildFields(FlowLogMessage msg) { return new HashMap<String, Object>() {{ put("account_id", msg.getAccountId()); put("interface_id", msg.getInterfaceId()); put("src_addr", msg.getSourceAddress()); put("dst_addr", msg.getDestinationAddress()); put("src_port", msg.getSourcePort()); put("dst_port", msg.getDestinationPort()); put("protocol_number", msg.getProtocolNumber()); put("protocol", protocolNumbers.lookup(msg.getProtocolNumber())); put("packets", msg.getPackets()); put("bytes", msg.getBytes()); put("capture_window_duration_seconds", Seconds.secondsBetween(msg.getCaptureWindowStart(), msg.getCaptureWindowEnd()).getSeconds()); put("action", msg.getAction()); put("log_status", msg.getLogStatus()); }}; }
private boolean shouldIgnoreNotification(@NotNull final Notification notification) { Notification lastNotification = mOrmManager.getLastNotification(); if (lastNotification == null) { return false; } boolean result = false; if (notification.getTitle().equals(lastNotification.getTitle())) { if (notification.getText().equals(lastNotification.getText())) { if (Seconds.secondsBetween(lastNotification.getCreated(), notification.getCreated()).getSeconds() < 60) { result = true; } } } return result; }
/** * @see DataType#DATE_TIME_SECONDS_SINCE_1960 * @see DataType#DATE_TIME_SECONDS_SINCE_1970 * @see DataType#DATE_TIME_SECONDS_SINCE_1980 */ static private SecondsSinceDate toSecondsSinceDate(Object value, LocalDate epoch){ if(value instanceof SecondsSinceDate){ SecondsSinceDate period = (SecondsSinceDate)value; if((period.getEpoch()).equals(epoch)){ return period; } Seconds difference = Seconds.secondsBetween(toMidnight(epoch), toMidnight(period.getEpoch())).plus(period.getSeconds()); return new SecondsSinceDate(epoch, difference); } throw new TypeCheckException(getSecondsDataType(epoch), value); }
@Test public void sniffTest() { final RDBI rdbi = new RDBI(new JedisPool("localhost")); final Map<String, RedisCacheTest.TestContainer> rMap = new RedisMap<>(RedisCacheTest.keyGenerator, RedisCacheTest.helper, rdbi, "mycache" + UUID.randomUUID().toString(), cachePrefix, Seconds.seconds(60).toStandardDuration()); final RedisCacheTest.TestContainer value1 = new RedisCacheTest.TestContainer(UUID.randomUUID()); final RedisCacheTest.TestContainer value2 = new RedisCacheTest.TestContainer(UUID.randomUUID()); rMap.put("value1", value1); rMap.put("value2", value2); assertEquals(rMap.get("value1"), value1); assertEquals(rMap.get("value2"), value2); }
public void compare() { DateTime dateTime1 = new DateTime(2014, 1, 1, 12, 00, 00); DateTime dateTime2 = new DateTime(2014, 1, 1, 12, 00, 01); // 时间之间的比较 boolean after = dateTime2.isAfter(dateTime1); LOGGER.info("is after" + after); // 两个时间之间相差的秒数 Seconds seconds = Seconds.secondsBetween(dateTime1, dateTime2); LOGGER.info(seconds.getSeconds() + ""); LOGGER.info("1:" + dateTime1.toString(YYYY_MM_DD_HH_MM_SS)); LOGGER.info("2:" + dateTime2.toString(YYYY_MM_DD_HH_MM_SS)); // 两个时间之间xiang相差的天数 Days days = Days.daysBetween(dateTime1, dateTime2); LOGGER.info("second:" + days.toStandardDuration().getStandardSeconds()); LOGGER.info(days.get(DurationFieldType.hours()) + ""); LOGGER.info(days.getFieldType().getName()); LOGGER.info(days.getPeriodType().getName()); LOGGER.info(days.toStandardSeconds().getSeconds() + ""); LOGGER.info(days.getDays() + ""); }
/** * Compare current session with another session * * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(Session o) { fmt.parseDateTime(this.end); fmt.parseDateTime(o.end); // ascending order return Seconds.secondsBetween(fmt.parseDateTime(o.end), fmt.parseDateTime(this.end)).getSeconds(); }
/** * Adding this wait as the Sybase ASE logs can fill up quickly if you execute a lot of DDLs * Hence, we put in a periodic check (currently going by every "maxLogCounter" updates executed) * to see if the log level exceeds a "stopLogSpaceThreshold". If so, we wait till it gets back * down to a "resumeLogSpaceThreshold" */ private void waitForLogSpace(Connection conn, JdbcHelper jdbc) { this.curLogCounter.incrementAndGet(); // only trigger the check every "maxLogCounter" checks if (this.curLogCounter.get() == maxLogCounter) { boolean firstTime = true; while (true) { int percentFull = getPercentLogFullInDb(conn, jdbc); int thresholdToCheck = firstTime ? stopLogSpaceThreshold : resumeLogSpaceThreshold; firstTime = false; if (percentFull < thresholdToCheck) { break; } else { try { Seconds seconds = Seconds.seconds(3); LOG.info(String .format("Pausing for %d seconds as the log level hit a high mark of %d; will resume when it gets back to %d", seconds.getSeconds(), percentFull, resumeLogSpaceThreshold)); Thread.sleep(seconds.getSeconds() * 1000); } catch (InterruptedException e) { throw new DeployerRuntimeException(e); } } } this.curLogCounter.set(0); // reset the log counter after doing the check } else if (this.curLogCounter.get() > maxLogCounter) { // in this case, some concurrent execution caused the ID to exceed the maxLogCounter. In this case, just // reset the counter to 0 (the thread that has the counter at the right value would execute this code this.curLogCounter.set(0); } }
/** * Migrate the Mongo database using the provided collection of commands. Will not apply versions already applied successfully. * * @return The trek state * @throws MongoTrekFailureException If the migration fails for whatever reason. */ public MongoTrekState migrate() throws MongoTrekFailureException { LOGGER.info("DATABASE MIGRATIONS"); MigrationCommands commands = commandsFactory().getCommands(migrationsFile); MongoTrekState state = migrationsService().getState(commands); if (!commands.hasMigrations()) { LOGGER.info(" No migrations to apply."); return state; } DateTime start = DateTime.now(); AtomicInteger successfulCount = new AtomicInteger(0); try { MongoTrekState.Pending pending = state.getPending(); if (!pending.hasPendingMigrations()) { LOGGER.info(" No migrations to apply."); return state; } logStatus("migrate", state.getCurrentVersion()); LOGGER.info(String.format(" Applying : [ %s ] -> [ %s ]", pending.getNextPendingVersion(), pending.getLastPendingVersion())); LOGGER.info(" Migrations :"); pending.getMigrations().stream().forEach(m -> applyMigration(successfulCount, m)); // Get state after migrations have been applied. return migrationsService().getState(commands); } catch (Exception e) { LOGGER.error("Error applying migration(s)", e); throw new MongoTrekFailureException(e); } finally { DateTime finish = DateTime.now(); LOGGER.info(String.format(">>> [ %d ] migrations applied in [ %d seconds ] <<<", successfulCount.get(), Seconds.secondsBetween(start, finish).getSeconds())); if (!this.providedDatabase) this.mongo.close(); } }
private int convertTime(String time) { PeriodFormatter formatter = ISOPeriodFormat.standard(); Period p = formatter.parsePeriod(time); Seconds s = p.toStandardSeconds(); return s.getSeconds(); }
@Restrict({@Group("STUDENT")}) public Result getExamRemainingTime(String hash) throws IOException { User user = getLoggedUser(); if (user == null) { return forbidden("sitnet_error_invalid_session"); } ExamEnrolment enrolment = Ebean.find(ExamEnrolment.class) .fetch("reservation") .fetch("reservation.machine") .fetch("reservation.machine.room") .fetch("exam") .fetch("externalExam") .where() .disjunction() .eq("exam.hash", hash) .eq("externalExam.hash", hash) .endJunction() .eq("user.id", user.getId()) .findUnique(); if (enrolment == null) { return notFound(); } final DateTime reservationStart = new DateTime(enrolment.getReservation().getStartAt()); final int durationMinutes = getDuration(enrolment); DateTime now = AppUtil.adjustDST(DateTime.now(), enrolment.getReservation()); final Seconds timeLeft = Seconds.secondsBetween(now, reservationStart.plusMinutes(durationMinutes)); return ok(String.valueOf(timeLeft.getSeconds())); }
private int secondsUntilNextMondayRun() { DateTime now = DateTime.now(); // Every Monday at 5AM UTC int adjustedHours = 5; if (!AppUtil.getDefaultTimeZone().isStandardOffset(now.getMillis())) { // Have the run happen an hour earlier to take care of DST offset adjustedHours -= 1; } DateTime nextRun = now.withHourOfDay(adjustedHours) .withMinuteOfHour(0) .withSecondOfMinute(0) .withMillisOfSecond(0) .plusWeeks(now.getDayOfWeek() == DateTimeConstants.MONDAY ? 0 : 1) .withDayOfWeek(DateTimeConstants.MONDAY); if (!nextRun.isAfter(now)) { nextRun = nextRun.plusWeeks(1); // now is a Monday after scheduled run time -> postpone } // Case for: now there's no DST but by next run there will be. if (adjustedHours == 5 && !AppUtil.getDefaultTimeZone().isStandardOffset(nextRun.getMillis())) { nextRun = nextRun.minusHours(1); } // Case for: now there's DST but by next run there won't be else if (adjustedHours != 5 && AppUtil.getDefaultTimeZone().isStandardOffset(nextRun.getMillis())) { nextRun = nextRun.plusHours(1); } Logger.info("Scheduled next weekly report to be run at {}", nextRun.toString()); // Increase delay with one second so that this won't fire off before intended time. This may happen because of // millisecond-level rounding issues and possibly cause resending of messages. return Seconds.secondsBetween(now, nextRun).getSeconds() + 1; }
private Optional<Seconds> getTimeToLive(final Authentication successfulAuthentication) { final UserInfo userInfo = UserInfo.extractFrom(successfulAuthentication); final Set<String> roles = AuthorityUtils.authorityListToSet(userInfo.getAuthorities()); if (roles.contains(SystemUser.Role.ROLE_REST.name())) { return Optional.empty(); } else if (roles.contains(SystemUser.Role.ROLE_ADMIN.name()) || roles.contains(SystemUser.Role.ROLE_MODERATOR.name())) { return Optional.of(securityConfigurationProperties.getRemeberMeTimeToLiveForModerator()); } else if (roles.contains(SystemUser.Role.ROLE_USER.name())) { return Optional.of(securityConfigurationProperties.getRememberMeTimeToLive()); } return Optional.empty(); }
@Test public void shouldAlwaysCommitWithUtcTimeZone() throws IOException { //given Widget widget = new Widget(); widget.setId(UUID.randomUUID()); widget.setName("name_1"); //when DateTimeZone.setDefault(DateTimeZone.forID("UTC")); javers.commit(COMMIT_AUTHOR, widget); DateTimeZone.setDefault(DateTimeZone.forID("Africa/Johannesburg")); widget.setName("name_2"); javers.commit(COMMIT_AUTHOR, widget); //then List<CdoSnapshot> snapshots = javers.findSnapshots( QueryBuilder.byClass(Widget.class).build()); assertEquals(2, snapshots.size()); LocalDateTime commitTime1 = snapshots.get(0).getCommitMetadata().getCommitDate(); LocalDateTime commitTime2 = snapshots.get(1).getCommitMetadata().getCommitDate(); int delta = Math.abs(Seconds.secondsBetween(commitTime1, commitTime2).getSeconds()); assertTrue(delta < 1); }
public static ReadablePeriod parsePeriodString(String periodStr) { ReadablePeriod period; char periodUnit = periodStr.charAt(periodStr.length() - 1); if (periodUnit == 'n') { return null; } int periodInt = Integer.parseInt(periodStr.substring(0, periodStr.length() - 1)); switch (periodUnit) { case 'M': period = Months.months(periodInt); break; case 'w': period = Weeks.weeks(periodInt); break; case 'd': period = Days.days(periodInt); break; case 'h': period = Hours.hours(periodInt); break; case 'm': period = Minutes.minutes(periodInt); break; case 's': period = Seconds.seconds(periodInt); break; default: throw new IllegalArgumentException("Invalid schedule period unit '" + periodUnit); } return period; }
public static ReadablePeriod parsePeriodString(String periodStr) { ReadablePeriod period; char periodUnit = periodStr.charAt(periodStr.length() - 1); if (periodStr.equals("null") || periodUnit == 'n') { return null; } int periodInt = Integer.parseInt(periodStr.substring(0, periodStr.length() - 1)); switch (periodUnit) { case 'y': period = Years.years(periodInt); break; case 'M': period = Months.months(periodInt); break; case 'w': period = Weeks.weeks(periodInt); break; case 'd': period = Days.days(periodInt); break; case 'h': period = Hours.hours(periodInt); break; case 'm': period = Minutes.minutes(periodInt); break; case 's': period = Seconds.seconds(periodInt); break; default: throw new IllegalArgumentException("Invalid schedule period unit '" + periodUnit); } return period; }
private static int getSecondsUntilTime(@NonNull final LocalTime time) { LocalDateTime alarmClock = LocalDate.now() .toLocalDateTime(time); if (alarmClock.isBefore(LocalDateTime.now())) { alarmClock = alarmClock.plusDays(1); } return Seconds.secondsBetween(LocalDateTime.now(), alarmClock).getSeconds(); }
private static int getSecondsUntilTime(@NonNull final Frequency frequency, final LocalDate lastUpdate) { final LocalTime time = LocalTime.parse(DEFAULT_TIME, DatabaseHelper.DB_TIME_FORMATTER); LocalDateTime alarmClock; if (null == lastUpdate) { // Never run before alarmClock = LocalDate.now().toLocalDateTime(time); } else { // Run before alarmClock = lastUpdate.toLocalDateTime(time); switch (frequency) { case DAILY: alarmClock = alarmClock.plusDays(1); break; case WEEKLY: alarmClock = alarmClock.plusWeeks(1); break; case MONTHLY: alarmClock = alarmClock.plusMonths(1); break; default: throw new IllegalStateException("Unknown value " + frequency); } } // May be pointing some time before now. while (alarmClock.isBefore(LocalDateTime.now())) { alarmClock = alarmClock.plusDays(1); } return Seconds.secondsBetween(LocalDateTime.now(), alarmClock).getSeconds(); }
private void formatSeconds(DateTime now, DateTime then, StringBuilder text) { int secondsBetween = Seconds.secondsBetween(now.toLocalTime(), then.toLocalTime()).getSeconds(); if (secondsBetween == 0) { text.append(context.getString(R.string.now)); } else if (secondsBetween > 0) { // in N seconds text.append(context.getResources().getQuantityString(R.plurals.carbon_inSeconds, secondsBetween, secondsBetween)); } else { // N seconds ago text.append(context.getResources().getQuantityString(R.plurals.carbon_secondsAgo, -secondsBetween, -secondsBetween)); } }
/** * TODO Temporary fix. Remove at some point. * * Ensures correctness of the storageStatus of this FileResource. * * If the status has been 'PENDING' for more than 1 second we check to see if the content may actually have been stored. * If this is the case the status is corrected to STORED. * * This method is a TEMPORARY fix for the for now unsolved issue with a race occurring between the Hibernate object cache * and the upload callback attempting to modify the FileResource object upon completion. * * Resolving that issue (likely by breaking the StorageStatus into a separate table) should make this method redundant. */ private FileResource ensureStorageStatus( FileResource fileResource ) { if ( fileResource != null && fileResource.getStorageStatus() == FileResourceStorageStatus.PENDING ) { Duration pendingDuration = new Duration( new DateTime( fileResource.getLastUpdated() ), DateTime.now() ); if ( pendingDuration.isLongerThan( Seconds.seconds( 1 ).toStandardDuration() ) ) { // Upload has been finished for 5+ seconds and is still PENDING. // Check if content has actually been stored and correct to STORED if this is the case. boolean contentIsStored = fileResourceContentStore.fileResourceContentExists( fileResource.getStorageKey() ); if ( contentIsStored ) { // We fix fileResource.setStorageStatus( FileResourceStorageStatus.STORED ); fileResourceStore.update( fileResource ); log.warn( "Corrected issue: FileResource '" + fileResource.getUid() + "' had storageStatus PENDING but content was actually stored." ); } } } return fileResource; }
/** * Set the year to the date of event */ public void setYear(int year) { int secondsBetweenStartAndStop = Seconds.secondsBetween( new DateTime(dateStart), new DateTime(dateStop)) .getSeconds(); dateStart = new DateTime(dateStart).withYear(year).toDate(); dateStop = new DateTime(dateStart).plusSeconds(secondsBetweenStartAndStop).toDate(); }
private String getFormattedDuration(int seconds) { Period period = new Period(Seconds.seconds(seconds)); PeriodFormatter periodFormatter = new PeriodFormatterBuilder() .printZeroAlways() .minimumPrintedDigits(2) .appendHours() .appendSeparator(":") .appendMinutes() .appendSeparator(":") .appendSeconds() .toFormatter(); return periodFormatter.print(period.normalizedStandard()); }
public static long getSecondsToWaitUntilStartTime(Optional<DateTime> startTime) { if (!startTime.isPresent()) { return 0L; } DateTime now = DateTime.now(); long seconds = Seconds.secondsBetween(now, startTime.get()).getSeconds(); if (seconds < 0L) { return 0L; } return seconds; }
@Test public void testBetween(){ Date start = DateUtils.parse("2016-12-06 17:35:30"); Date end = DateUtils.parse("2016-12-06 17:35:33"); Period period = JodatimeUtils.between(start, end); assertThat(period.getSeconds(), equalTo(Seconds.THREE.getSeconds())); assertThat(Seconds.secondsBetween(new LocalDateTime(start), new LocalDateTime(end)), equalTo(Seconds.THREE)); }
public static Seconds getSecondsUntilNextInterval(int intervalInHours) { DateTime currentDateTime = DateTime.now(); int hoursUntilNextInterval = (23 - currentDateTime.getHourOfDay()) % intervalInHours; int hour = currentDateTime.getHourOfDay() + hoursUntilNextInterval; DateTime scheduledTime = new DateTime(currentDateTime.getYear(), currentDateTime.getMonthOfYear(), currentDateTime.getDayOfMonth(), hour, 55, currentDateTime.getZone()); return Seconds.secondsBetween(currentDateTime, scheduledTime); }
@Test public void longIntervals() { for (int index = 0; index < LONG_INTERVALS_EXPECTED_VALUES.length; index++) { DateTimeUtils.setCurrentMillisFixed(new DateTime(2015, 8, 1, LONG_INTERVALS_EXPECTED_VALUES[index][0], 0).getMillis()); Seconds result = TimeUtil.getSecondsUntilNextInterval(LONG_INTERVAL); assertThat(result.getSeconds(), Matchers.is(LONG_INTERVALS_EXPECTED_VALUES[index][1])); } }