Java Code Examples for java.time.ZonedDateTime#truncatedTo()

The following examples show how to use java.time.ZonedDateTime#truncatedTo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SimpleScheduler.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
ZonedDateTime evaluate(ZonedDateTime now) {
    if (now.isBefore(start)) {
        return null;
    }
    if (lastFireTime == null) {
        // First execution
        lastFireTime = now.truncatedTo(ChronoUnit.SECONDS);
        return now;
    }
    if (ChronoUnit.MILLIS.between(lastFireTime, now) >= interval) {
        ZonedDateTime scheduledFireTime = lastFireTime.plus(Duration.ofMillis(interval));
        lastFireTime = now.truncatedTo(ChronoUnit.SECONDS);
        return scheduledFireTime;
    }
    return null;
}
 
Example 2
Source File: ScheduledTaskTest.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@Test
public void testNextFormattedRuntime() {
    final Long millisecondsToNextRun = 10000L;
    ZonedDateTime currentUTCTime = ZonedDateTime.now(ZoneOffset.UTC);
    ZonedDateTime expectedDateTime = currentUTCTime.plus(millisecondsToNextRun, ChronoUnit.MILLIS);
    int seconds = expectedDateTime.getSecond();
    if (seconds >= 30) {
        expectedDateTime = expectedDateTime.truncatedTo(ChronoUnit.MINUTES).plusMinutes(1);
    } else {
        expectedDateTime = expectedDateTime.truncatedTo(ChronoUnit.MINUTES);
    }
    String expectedNextRunTime = expectedDateTime.format(DateTimeFormatter.ofPattern(ScheduledTask.FORMAT_PATTERN)) + " UTC";

    Mockito.doReturn(future).when(taskScheduler).schedule(Mockito.any(), Mockito.any(CronTrigger.class));
    Mockito.when(future.getDelay(TimeUnit.MILLISECONDS)).thenReturn(millisecondsToNextRun);
    task.scheduleExecution(validCronExpression);
    Optional<String> nextRunTime = task.getFormatedNextRunTime();
    assertTrue(nextRunTime.isPresent());
    String nextTime = nextRunTime.get();
    assertEquals(expectedNextRunTime, nextTime);
}
 
Example 3
Source File: ScheduledTask.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
public Optional<String> getFormatedNextRunTime() {
    Optional<Long> msToNextRun = getMillisecondsToNextRun();
    if (msToNextRun.isPresent()) {

        ZonedDateTime currentUTCTime = ZonedDateTime.now(ZoneOffset.UTC);
        ZonedDateTime nextRunTime = currentUTCTime.plus(msToNextRun.get(), ChronoUnit.MILLIS);
        int seconds = nextRunTime.getSecond();
        if (seconds >= 30) {
            nextRunTime = nextRunTime.truncatedTo(ChronoUnit.MINUTES).plusMinutes(1);
        } else {
            nextRunTime = nextRunTime.truncatedTo(ChronoUnit.MINUTES);
        }
        String formattedString = nextRunTime.format(DateTimeFormatter.ofPattern(FORMAT_PATTERN));
        return Optional.of(formattedString + " UTC");
    }
    return Optional.empty();
}
 
Example 4
Source File: TimeTodayQueryMacroHandler.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> getParams() {
    Map<String, Object> params = new HashMap<>();
    for (ArgDef argDef : argDefs) {
        Class javaType = expandedParamTypes.get(argDef.firstParamName);
        if (javaType == null)
            throw new RuntimeException(String.format("Type of parameter %s not resolved", argDef.firstParamName));
        ZonedDateTime zonedDateTime = timeSource.now();
        if (transformations.isDateTypeSupportsTimeZones(javaType)) {
            zonedDateTime = zonedDateTime.withZoneSameInstant(argDef.timeZone.toZoneId());
        }
        ZonedDateTime firstZonedDateTime = zonedDateTime.truncatedTo(ChronoUnit.DAYS);
        ZonedDateTime secondZonedDateTime = firstZonedDateTime.plusDays(1);

        params.put(argDef.firstParamName, transformations.transformFromZDT(firstZonedDateTime, javaType));
        params.put(argDef.secondParamName, transformations.transformFromZDT(secondZonedDateTime, javaType));
    }
    return params;
}
 
Example 5
Source File: MultipathPolicyTracker.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private long getDailyNonDefaultDataUsage() {
    final ZonedDateTime end =
            ZonedDateTime.ofInstant(mClock.instant(), ZoneId.systemDefault());
    final ZonedDateTime start = end.truncatedTo(ChronoUnit.DAYS);

    final long bytes = getNetworkTotalBytes(
            start.toInstant().toEpochMilli(),
            end.toInstant().toEpochMilli());
    if (DBG) Slog.d(TAG, "Non-default data usage: " + bytes);
    return bytes;
}
 
Example 6
Source File: Email.java    From skara with GNU General Public License v2.0 5 votes vote down vote up
Email(EmailAddress id, ZonedDateTime date, List<EmailAddress> recipients, EmailAddress author, EmailAddress sender, String subject, String body, Map<String, String> headers) {
    this.id = id;
    this.date = date.truncatedTo(ChronoUnit.SECONDS);
    this.recipients = new ArrayList<>(recipients);
    this.sender = sender;
    this.subject = subject;
    this.body = body;
    this.author = author;
    this.headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    this.headers.putAll(headers);
}
 
Example 7
Source File: DateEqualsMacroHandler.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> getParams() {
    Map<String, Object> params = new HashMap<>();
    for (MacroArgsDateEquals paramArg : paramArgs) {
        Class javaType;
        ZonedDateTime zonedDateTime;
        String firstparamName = paramArg.getParamName();
        String secondParamName = paramArg.getSecondParamName();
        TimeZone timeZone = paramArg.getTimeZone();
        if (timeZone == null)
            timeZone = TimeZone.getDefault();
        if (paramArg.isNow()) {
            zonedDateTime = timeSource.now();
            javaType = expandedParamTypes.get(firstparamName);
            if (javaType == null)
                throw new RuntimeException(String.format("Type of parameter %s not resolved", firstparamName));
        } else {
            Object date = namedParameters.get(firstparamName);
            if (date == null)
                throw new RuntimeException(String.format("Parameter %s not found for macro", firstparamName));
            javaType = date.getClass();
            zonedDateTime = transformations.transformToZDT(date);
        }
        if (transformations.isDateTypeSupportsTimeZones(javaType)) {
            zonedDateTime = zonedDateTime.withZoneSameInstant(timeZone.toZoneId());
        }
        zonedDateTime = zonedDateTime.plusDays(paramArg.getOffset()).truncatedTo(ChronoUnit.DAYS);
        ZonedDateTime firstZonedDateTime = zonedDateTime.truncatedTo(ChronoUnit.DAYS);
        ZonedDateTime secondZonedDateTime = firstZonedDateTime.plusDays(1);
        params.put(firstparamName, transformations.transformFromZDT(firstZonedDateTime, javaType));
        params.put(secondParamName, transformations.transformFromZDT(secondZonedDateTime, javaType));
    }
    return params;
}
 
Example 8
Source File: DateResolutionFormatter.java    From james-project with Apache License 2.0 5 votes vote down vote up
public static ZonedDateTime computeLowerDate(ZonedDateTime date, SearchQuery.DateResolution resolution) {
    switch (resolution) {
        case Year:
            return date.truncatedTo(ChronoUnit.DAYS).withDayOfYear(1);
        case Month:
            return date.truncatedTo(ChronoUnit.DAYS).withDayOfMonth(1);
        default:
            return date.truncatedTo(convertDateResolutionField(resolution));
    }
}
 
Example 9
Source File: RecordManager.java    From PlayTimeTracker with MIT License 5 votes vote down vote up
private UUID updateNonAccumulative(UUID id) {
    if (id == null) return null;
    Main.debug("updateNonAccumulative: " + id.toString());
    DatabaseRecord rec = db.getRecord(id);
    if (rec == null) {
        db.createRecord(id, ZonedDateTime.now());
    } else {
        ZonedDateTime currentTime = ZonedDateTime.now();
        ZonedDateTime lastSeen = rec.lastSeen;
        rec.lastSeen = currentTime;
        long duration = Duration.between(lastSeen, currentTime).toMillis();
        if (duration <= 0) return null;

        ZonedDateTime startOfToday = currentTime.truncatedTo(ChronoUnit.DAYS);
        ZonedDateTime startOfWeek = currentTime.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).truncatedTo(ChronoUnit.DAYS);
        ZonedDateTime startOfMonth = currentTime.with(TemporalAdjusters.firstDayOfMonth()).truncatedTo(ChronoUnit.DAYS);

        if (startOfToday.isAfter(lastSeen)) {
            Main.debug("Daily time reset: " + id.toString());
            rec.completedDailyMissions = new HashSet<>();
            rec.dailyTime = 0;
        }
        if (startOfWeek.isAfter(lastSeen)) {
            Main.debug("Weekly time reset: " + id.toString());
            rec.completedWeeklyMissions = new HashSet<>();
            rec.weeklyTime = 0;
        }
        if (startOfMonth.isAfter(lastSeen)) {
            Main.debug("Monthly time reset: " + id.toString());
            rec.completedMonthlyMissions = new HashSet<>();
            rec.monthlyTime = 0;
        }
    }
    return id;
}
 
Example 10
Source File: ExecutionTimeQuartzIntegrationTest.java    From cron-utils with Apache License 2.0 4 votes vote down vote up
private ZonedDateTime truncateToSeconds(final ZonedDateTime dateTime) {
    return dateTime.truncatedTo(ChronoUnit.SECONDS);
}
 
Example 11
Source File: SingleExecutionTime.java    From cron-utils with Apache License 2.0 4 votes vote down vote up
private ExecutionTimeResult potentialPreviousClosestMatch(final ZonedDateTime date) throws NoSuchValueException {
    //int startyear = cronDefinition.getFieldDefinition(CronFieldName.YEAR).getConstraints().getStartRange();
    //final List<Integer> year = yearsValueGenerator.generateCandidates(startyear, date.getYear());
    final List<Integer> year = yearsValueGenerator.generateCandidates(date.getYear(), date.getYear());
    final Optional<TimeNode> optionalDays = generateDays(cronDefinition, date);
    TimeNode days;
    if (optionalDays.isPresent()) {
        days = optionalDays.get();
    } else {
        return new ExecutionTimeResult(toEndOfPreviousMonth(date), false);
    }
    final int highestMonth = months.getValues().get(months.getValues().size() - 1);
    final int highestDay = days.getValues().get(days.getValues().size() - 1);
    final int highestHour = hours.getValues().get(hours.getValues().size() - 1);
    final int highestMinute = minutes.getValues().get(minutes.getValues().size() - 1);
    final int highestSecond = seconds.getValues().get(seconds.getValues().size() - 1);

    if (year.isEmpty()) {
        return getPreviousPotentialYear(date, days, highestMonth, highestDay, highestHour, highestMinute, highestSecond);
    }
    //TODO Issue 305
    /*
    else{
        if(!year.contains(date.getYear())){
            Optional<Integer> validprevyear = year.stream().filter(y->y<date.getYear()).max(Integer::compareTo);
            if(validprevyear.isPresent()){
                int minus = date.getYear()-validprevyear.get();
                return getPreviousPotentialYear(date.minusYears(minus), days, highestMonth, highestDay, highestHour, highestMinute, highestSecond);
            }else{
                return getPreviousPotentialYear(date.minusYears(1), days, highestMonth, highestDay, highestHour, highestMinute, highestSecond);
            }
        }
    }
    */
    if (!months.getValues().contains(date.getMonthValue())) {
        return getPreviousPotentialMonth(date, highestDay, highestHour, highestMinute, highestSecond);
    }
    if (!days.getValues().contains(date.getDayOfMonth())) {
        return getPreviousPotentialDayOfMonth(date, days, highestHour, highestMinute, highestSecond);
    }
    if (!hours.getValues().contains(date.getHour())) {
        return getPreviousPotentialHour(date);
    }
    if (!minutes.getValues().contains(date.getMinute())) {
        return getPreviousPotentialMinute(date);
    }
    if (!seconds.getValues().contains(date.getSecond())) {
        return getPreviousPotentialSecond(date);
    }
    return new ExecutionTimeResult(date.truncatedTo(SECONDS), true);
}
 
Example 12
Source File: ExpChartController.java    From logbook-kai with MIT License 4 votes vote down vote up
@Override
public ZonedDateTime max(ZonedDateTime base) {
    return base.truncatedTo(ChronoUnit.DAYS);
}
 
Example 13
Source File: ExpChartController.java    From logbook-kai with MIT License 4 votes vote down vote up
@Override
public ZonedDateTime min(ZonedDateTime base) {
    return base.truncatedTo(ChronoUnit.DAYS);
}
 
Example 14
Source File: RecordManager.java    From PlayTimeTracker with MIT License 4 votes vote down vote up
/**
 * Update the time statistic for single uuid
 * database not flushed
 * fallback to updateNonAccumulative if id is in AFK state
 * prerequisite: player is online
 *
 * @param id the uuid to be updated
 * @return id if changed, null if not
 */
private UUID updateAccumulative(UUID id) {
    if (id == null) return null;
    if (Main.isAFK(id)) {
        Main.debug("updateNonAccumulative due player AFK: " + id.toString());
        return updateNonAccumulative(id);
    }
    Main.debug("updateAccumulative: " + id.toString());
    DatabaseRecord rec = db.getRecord(id);
    if (rec == null) {
        db.createRecord(id, ZonedDateTime.now());
    } else {
        ZonedDateTime currentTime = ZonedDateTime.now();
        ZonedDateTime lastSeen = rec.lastSeen;
        rec.lastSeen = currentTime;
        long duration = Duration.between(lastSeen, currentTime).toMillis();
        if (duration <= 0) return null;
        Main.debug(String.format("Time duration: %d (%s ~ %s)", duration, lastSeen.toString(), currentTime.toString()));

        ZonedDateTime startOfToday = currentTime.truncatedTo(ChronoUnit.DAYS);
        ZonedDateTime startOfWeek = currentTime.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).truncatedTo(ChronoUnit.DAYS);
        ZonedDateTime startOfMonth = currentTime.with(TemporalAdjusters.firstDayOfMonth()).truncatedTo(ChronoUnit.DAYS);

        if (startOfToday.isAfter(lastSeen)) {
            Main.debug("Daily time reset: " + id.toString());
            rec.completedDailyMissions = new HashSet<>();
            rec.dailyTime = Duration.between(startOfToday, currentTime).toMillis();
        } else {
            rec.dailyTime += duration;
        }
        if (startOfWeek.isAfter(lastSeen)) {
            Main.debug("Weekly time reset: " + id.toString());
            rec.completedWeeklyMissions = new HashSet<>();
            rec.weeklyTime = 0;
        } else {
            rec.weeklyTime += duration;
        }
        if (startOfMonth.isAfter(lastSeen)) {
            Main.debug("Daily time reset: " + id.toString());
            rec.completedMonthlyMissions = new HashSet<>();
            rec.monthlyTime = 0;
        } else {
            rec.monthlyTime += duration;
        }
        rec.totalTime += duration;

        // update recurrence records
        if (db.recurrenceMap.containsKey(id)) {
            Map<String, Long> tmp = db.recurrenceMap.get(id);
            for (String n : tmp.keySet()) {
                tmp.put(n, tmp.get(n) + duration);
            }
        }
    }
    return id;
}
 
Example 15
Source File: ModelSupport.java    From FHIR with Apache License 2.0 4 votes vote down vote up
/**
 * @return a copy of the passed ZonedDateTime with the time truncated to {@code unit}
 */
public static ZonedDateTime truncateTime(ZonedDateTime dateTime, ChronoUnit unit) {
    return dateTime == null ? null : dateTime.truncatedTo(unit);
}
 
Example 16
Source File: BitflyerAdviser.java    From cryptotrader with GNU Affero General Public License v3.0 3 votes vote down vote up
@VisibleForTesting
BigDecimal calculateSwapRate(Context context, Request request, BigDecimal dailyRate) {

    if (dailyRate == null) {
        return ZERO;
    }

    Instant now = request.getCurrentTime();

    if (now == null) {
        return ZERO;
    }

    ZonedDateTime expiry = context.getExpiry(Key.from(request));

    if (expiry == null) {
        return ZERO; // Not an expiry product.
    }

    ZonedDateTime sod = expiry.truncatedTo(ChronoUnit.DAYS);

    Duration swapFree = Duration.between(sod, expiry);

    Duration maturity = Duration.between(request.getCurrentTime(), expiry);

    if (maturity.compareTo(swapFree) < 0) {
        return ZERO; // Expiring without swap.
    }

    long swaps = maturity.toDays();

    double rate = Math.pow(ONE.add(dailyRate).doubleValue(), swaps) - 1;

    return BigDecimal.valueOf(rate).setScale(SCALE, UP);

}
 
Example 17
Source File: DateTimeExtensions.java    From groovy with Apache License 2.0 2 votes vote down vote up
/**
 * Returns an {@link java.time.ZonedDateTime} with the time portion cleared.
 *
 * @param self a ZonedDateTime
 * @return a ZonedDateTime
 * @since 2.5.0
 */
public static ZonedDateTime clearTime(final ZonedDateTime self) {
    return self.truncatedTo(DAYS);
}
 
Example 18
Source File: DateTimeRange.java    From constellation with Apache License 2.0 2 votes vote down vote up
/**
 * A range with the specified ZoneDateTime instances.
 *
 * @param zstart the start of the time range.
 * @param zend the end of the time range.
 */
public DateTimeRange(final ZonedDateTime zstart, final ZonedDateTime zend) {
    this.period = null;
    this.zstart = zstart.truncatedTo(ChronoUnit.SECONDS);
    this.zend = zend.truncatedTo(ChronoUnit.SECONDS);
}