Search in sources :

Example 6 with ChronoUnit

use of java.time.temporal.ChronoUnit in project jphp by jphp-compiler.

the class Adjusters method relativeUnit.

public static Pair<TemporalAdjuster, TemporalField> relativeUnit(DateTimeParserContext ctx, String unit, final long value) {
    ChronoUnit chronoUnit;
    TemporalField field;
    switch(unit.toLowerCase()) {
        case "year":
        case "years":
            return Pair.of(temporal -> {
                try {
                    Temporal ret = temporal.plus(value, YEARS);
                    ctx.addRelativeContributor(unit, value);
                    return ret;
                } catch (DateTimeException e) {
                    ValueRange range = YEAR.range();
                    long validYear = value < range.getMinimum() ? range.getMinimum() : range.getMaximum();
                    return temporal.with(YEAR, validYear);
                }
            }, YEAR);
        case "month":
        case "months":
            chronoUnit = MONTHS;
            field = MONTH_OF_YEAR;
            break;
        case "day":
        case "days":
            chronoUnit = DAYS;
            field = DAY_OF_MONTH;
            break;
        case "hour":
        case "hours":
            chronoUnit = HOURS;
            field = HOUR_OF_DAY;
            return Pair.of(temporal -> {
                ctx.addRelativeContributor("hour", value);
                if (!ctx.isModifiedTimezone() && temporal instanceof ZonedDateTime) {
                    ZonedDateTime dateTime = (ZonedDateTime) temporal;
                    return dateTime.toLocalDateTime().plusHours(value).atZone(dateTime.getZone());
                }
                return temporal.plus(value, chronoUnit);
            }, field);
        case "minute":
        case "minutes":
        case "min":
        case "mins":
            chronoUnit = MINUTES;
            field = MINUTE_OF_HOUR;
            break;
        case "second":
        case "seconds":
        case "sec":
        case "secs":
            chronoUnit = SECONDS;
            field = SECOND_OF_MINUTE;
            break;
        case "millisecond":
        case "milliseconds":
        case "msecs":
        case "msec":
        case "ms":
            chronoUnit = MILLIS;
            field = MILLI_OF_SECOND;
            break;
        case "microsecond":
        case "microseconds":
        case "usec":
        case "usecs":
        case "µs":
        case "µsec":
        case "µsecs":
            chronoUnit = MICROS;
            field = MICRO_OF_SECOND;
            break;
        case "week":
        case "weeks":
            chronoUnit = WEEKS;
            field = DAY_OF_MONTH;
            break;
        case "fortnight":
        case "forthnight":
        case "fortnights":
        case "forthnights":
            return Pair.of(temporal -> {
                long amountToAdd = value * 14L;
                ctx.addRelativeContributor("day", amountToAdd);
                return temporal.plus(amountToAdd, DAYS);
            }, DAY_OF_MONTH);
        case "weekday":
        case "weekdays":
            return Pair.of(plusBusinessDays(value), DAY_OF_MONTH);
        default:
            throw new IllegalArgumentException("Unknown unit: " + unit);
    }
    return Pair.of(temporal -> {
        String chronoUnitAsString = chronoUnit.toString();
        String u = chronoUnitAsString.toLowerCase().substring(0, chronoUnitAsString.length() - 1);
        ctx.addRelativeContributor(u, value);
        return temporal.plus(value, chronoUnit);
    }, field);
}
Also used : ValueRange(java.time.temporal.ValueRange) TemporalField(java.time.temporal.TemporalField) DateTimeException(java.time.DateTimeException) Temporal(java.time.temporal.Temporal) ZonedDateTime(java.time.ZonedDateTime) ChronoUnit(java.time.temporal.ChronoUnit)

Example 7 with ChronoUnit

use of java.time.temporal.ChronoUnit in project org.csstudio.display.builder by kasemir.

the class TemporalRoundingTest method testRandomRounding.

@Test
public void testRandomRounding() {
    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss (z, 'UTC' Z)");
    final ZonedDateTime start = ZonedDateTime.now();
    for (ChronoUnit unit : SUPPORTED_UNITS) {
        final int amount = (int) (Math.random() * 60);
        final ZonedDateTime rd = start.with(zonedDateTimerRoundedToNextOrSame(unit, amount));
        System.out.println(formatter.format(start) + " rounded by " + amount + " " + unit + " -> " + formatter.format(rd));
    }
}
Also used : ZonedDateTime(java.time.ZonedDateTime) DateTimeFormatter(java.time.format.DateTimeFormatter) ChronoUnit(java.time.temporal.ChronoUnit) Test(org.junit.Test)

Example 8 with ChronoUnit

use of java.time.temporal.ChronoUnit in project HolandaCatalinaFw by javaito.

the class Collector method collect.

/**
 * This method is the public interface to collect information into the collector.
 * This method calculates the time id to index de information using the periodicity
 * of the collector then call the onCollector method to execute the internal collecting algorithm.
 * @param collectibleObject Collectible object.
 */
public final void collect(C collectibleObject) {
    LocalDateTime localDateTime = LocalDateTime.now();
    ChronoUnit chronoUnit = null;
    switch(getPeriodicity()) {
        case MINUTE:
            chronoUnit = ChronoUnit.MINUTES;
            break;
        case HOUR:
            chronoUnit = ChronoUnit.HOURS;
            break;
        case DAY:
            chronoUnit = ChronoUnit.DAYS;
            break;
        case WEEK:
            chronoUnit = ChronoUnit.WEEKS;
            break;
        case MONTH:
            chronoUnit = ChronoUnit.MONTHS;
            break;
        case YEAR:
            chronoUnit = ChronoUnit.YEARS;
            break;
    }
    Long timeId = 0L;
    if (chronoUnit != null) {
        timeId = Date.from(localDateTime.truncatedTo(chronoUnit).atZone(ZoneId.systemDefault()).toInstant()).getTime();
    }
    onCollect(collectibleObject, timeId);
}
Also used : LocalDateTime(java.time.LocalDateTime) ChronoUnit(java.time.temporal.ChronoUnit)

Example 9 with ChronoUnit

use of java.time.temporal.ChronoUnit in project Bytecoder by mirkosertic.

the class LocalDateTime method until.

/**
 * Calculates the amount of time until another date-time in terms of the specified unit.
 * <p>
 * This calculates the amount of time between two {@code LocalDateTime}
 * objects in terms of a single {@code TemporalUnit}.
 * The start and end points are {@code this} and the specified date-time.
 * The result will be negative if the end is before the start.
 * The {@code Temporal} passed to this method is converted to a
 * {@code LocalDateTime} using {@link #from(TemporalAccessor)}.
 * For example, the amount in days between two date-times can be calculated
 * using {@code startDateTime.until(endDateTime, DAYS)}.
 * <p>
 * The calculation returns a whole number, representing the number of
 * complete units between the two date-times.
 * For example, the amount in months between 2012-06-15T00:00 and 2012-08-14T23:59
 * will only be one month as it is one minute short of two months.
 * <p>
 * There are two equivalent ways of using this method.
 * The first is to invoke this method.
 * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
 * <pre>
 *   // these two lines are equivalent
 *   amount = start.until(end, MONTHS);
 *   amount = MONTHS.between(start, end);
 * </pre>
 * The choice should be made based on which makes the code more readable.
 * <p>
 * The calculation is implemented in this method for {@link ChronoUnit}.
 * The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS},
 * {@code MINUTES}, {@code HOURS} and {@code HALF_DAYS}, {@code DAYS},
 * {@code WEEKS}, {@code MONTHS}, {@code YEARS}, {@code DECADES},
 * {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS} are supported.
 * Other {@code ChronoUnit} values will throw an exception.
 * <p>
 * If the unit is not a {@code ChronoUnit}, then the result of this method
 * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
 * passing {@code this} as the first argument and the converted input temporal
 * as the second argument.
 * <p>
 * This instance is immutable and unaffected by this method call.
 *
 * @param endExclusive  the end date, exclusive, which is converted to a {@code LocalDateTime}, not null
 * @param unit  the unit to measure the amount in, not null
 * @return the amount of time between this date-time and the end date-time
 * @throws DateTimeException if the amount cannot be calculated, or the end
 *  temporal cannot be converted to a {@code LocalDateTime}
 * @throws UnsupportedTemporalTypeException if the unit is not supported
 * @throws ArithmeticException if numeric overflow occurs
 */
@Override
public long until(Temporal endExclusive, TemporalUnit unit) {
    LocalDateTime end = LocalDateTime.from(endExclusive);
    if (unit instanceof ChronoUnit) {
        if (unit.isTimeBased()) {
            long amount = date.daysUntil(end.date);
            if (amount == 0) {
                return time.until(end.time, unit);
            }
            long timePart = end.time.toNanoOfDay() - time.toNanoOfDay();
            if (amount > 0) {
                // safe
                amount--;
                // safe
                timePart += NANOS_PER_DAY;
            } else {
                // safe
                amount++;
                // safe
                timePart -= NANOS_PER_DAY;
            }
            switch((ChronoUnit) unit) {
                case NANOS:
                    amount = Math.multiplyExact(amount, NANOS_PER_DAY);
                    break;
                case MICROS:
                    amount = Math.multiplyExact(amount, MICROS_PER_DAY);
                    timePart = timePart / 1000;
                    break;
                case MILLIS:
                    amount = Math.multiplyExact(amount, MILLIS_PER_DAY);
                    timePart = timePart / 1_000_000;
                    break;
                case SECONDS:
                    amount = Math.multiplyExact(amount, SECONDS_PER_DAY);
                    timePart = timePart / NANOS_PER_SECOND;
                    break;
                case MINUTES:
                    amount = Math.multiplyExact(amount, MINUTES_PER_DAY);
                    timePart = timePart / NANOS_PER_MINUTE;
                    break;
                case HOURS:
                    amount = Math.multiplyExact(amount, HOURS_PER_DAY);
                    timePart = timePart / NANOS_PER_HOUR;
                    break;
                case HALF_DAYS:
                    amount = Math.multiplyExact(amount, 2);
                    timePart = timePart / (NANOS_PER_HOUR * 12);
                    break;
            }
            return Math.addExact(amount, timePart);
        }
        LocalDate endDate = end.date;
        if (endDate.isAfter(date) && end.time.isBefore(time)) {
            endDate = endDate.minusDays(1);
        } else if (endDate.isBefore(date) && end.time.isAfter(time)) {
            endDate = endDate.plusDays(1);
        }
        return date.until(endDate, unit);
    }
    return unit.between(this, end);
}
Also used : ChronoLocalDateTime(java.time.chrono.ChronoLocalDateTime) ChronoUnit(java.time.temporal.ChronoUnit)

Example 10 with ChronoUnit

use of java.time.temporal.ChronoUnit in project wildfly-swarm by wildfly-swarm.

the class SynchronousCircuitBreaker method isAfterDelay.

private boolean isAfterDelay() {
    long openedAt = circuitOpenedAt.get();
    long delay = config.get(CircuitBreakerConfig.DELAY);
    if (delay == 0) {
        return true;
    }
    ChronoUnit delayUnit = config.get(CircuitBreakerConfig.DELAY_UNIT);
    long elapsed;
    if (delayUnit.equals(ChronoUnit.MILLIS)) {
        elapsed = System.currentTimeMillis() - openedAt;
    } else {
        Instant start = Instant.ofEpochMilli(openedAt);
        Instant now = Instant.now();
        elapsed = delayUnit.between(start, now);
    }
    return elapsed >= delay;
}
Also used : Instant(java.time.Instant) ChronoUnit(java.time.temporal.ChronoUnit)

Aggregations

ChronoUnit (java.time.temporal.ChronoUnit)42 Test (org.junit.jupiter.api.Test)11 Test (org.junit.Test)6 LocalDateTime (java.time.LocalDateTime)5 Matcher (java.util.regex.Matcher)5 Duration (java.time.Duration)4 Map (java.util.Map)4 ImmutableMap (com.google.common.collect.ImmutableMap)3 ChronoLocalDateTime (java.time.chrono.ChronoLocalDateTime)3 ArrayList (java.util.ArrayList)3 Pattern (java.util.regex.Pattern)3 Given (cucumber.api.java.en.Given)2 CommandSubscriber (de.nikos410.discordBot.util.modular.annotations.CommandSubscriber)2 CommandSubscriber (de.nikos410.discordbot.framework.annotations.CommandSubscriber)2 CommandUtils (de.nikos410.discordbot.util.CommandUtils)2 FaultToleranceService (fish.payara.microprofile.faulttolerance.FaultToleranceService)2 Instant (java.time.Instant)2 ZonedDateTime (java.time.ZonedDateTime)2 DateTimeFormatter (java.time.format.DateTimeFormatter)2 ScheduledFuture (java.util.concurrent.ScheduledFuture)2