Search in sources :

Example 11 with ChronoUnit

use of java.time.temporal.ChronoUnit in project config by typesafehub.

the class SimpleConfig method parsePeriod.

/**
 * Parses a period string. If no units are specified in the string, it is
 * assumed to be in days. The returned period is in days.
 * The purpose of this function is to implement the period-related methods
 * in the ConfigObject interface.
 *
 * @param input
 *            the string to parse
 * @param originForException
 *            origin of the value being parsed
 * @param pathForException
 *            path to include in exceptions
 * @return duration in days
 * @throws ConfigException
 *             if string is invalid
 */
public static Period parsePeriod(String input, ConfigOrigin originForException, String pathForException) {
    String s = ConfigImplUtil.unicodeTrim(input);
    String originalUnitString = getUnits(s);
    String unitString = originalUnitString;
    String numberString = ConfigImplUtil.unicodeTrim(s.substring(0, s.length() - unitString.length()));
    ChronoUnit units;
    // is more helpful if we check it here.
    if (numberString.length() == 0)
        throw new ConfigException.BadValue(originForException, pathForException, "No number in period value '" + input + "'");
    if (unitString.length() > 2 && !unitString.endsWith("s"))
        unitString = unitString + "s";
    // note that this is deliberately case-sensitive
    if (unitString.equals("") || unitString.equals("d") || unitString.equals("days")) {
        units = ChronoUnit.DAYS;
    } else if (unitString.equals("w") || unitString.equals("weeks")) {
        units = ChronoUnit.WEEKS;
    } else if (unitString.equals("m") || unitString.equals("mo") || unitString.equals("months")) {
        units = ChronoUnit.MONTHS;
    } else if (unitString.equals("y") || unitString.equals("years")) {
        units = ChronoUnit.YEARS;
    } else {
        throw new ConfigException.BadValue(originForException, pathForException, "Could not parse time unit '" + originalUnitString + "' (try d, w, mo, y)");
    }
    try {
        return periodOf(Integer.parseInt(numberString), units);
    } catch (NumberFormatException e) {
        throw new ConfigException.BadValue(originForException, pathForException, "Could not parse duration number '" + numberString + "'");
    }
}
Also used : ConfigException(com.typesafe.config.ConfigException) ChronoUnit(java.time.temporal.ChronoUnit)

Example 12 with ChronoUnit

use of java.time.temporal.ChronoUnit in project j2objc by google.

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 13 with ChronoUnit

use of java.time.temporal.ChronoUnit in project Aeron by real-logic.

the class ClusterEventLoggerTest method logElectionStateChange.

@Test
void logElectionStateChange() {
    final int offset = ALIGNMENT * 4;
    logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, offset);
    final ChronoUnit from = ChronoUnit.ERAS;
    final ChronoUnit to = null;
    final int memberId = 18;
    final int leaderId = -1;
    final long candidateTermId = 29L;
    final long leadershipTermId = 0L;
    final long logPosition = 100L;
    final long logLeadershipTermId = -9L;
    final long appendPosition = 16 * 1024L;
    final long catchupPosition = 8192L;
    final int length = electionStateChangeLength(from, to);
    logger.logElectionStateChange(from, to, memberId, leaderId, candidateTermId, leadershipTermId, logPosition, logLeadershipTermId, appendPosition, catchupPosition);
    verifyLogHeader(logBuffer, offset, ELECTION_STATE_CHANGE.toEventCodeId(), length, length);
    int index = encodedMsgOffset(offset) + LOG_HEADER_LENGTH;
    assertEquals(memberId, logBuffer.getInt(index, LITTLE_ENDIAN));
    index += SIZE_OF_INT;
    assertEquals(leaderId, logBuffer.getInt(index, LITTLE_ENDIAN));
    index += SIZE_OF_INT;
    assertEquals(candidateTermId, logBuffer.getLong(index, LITTLE_ENDIAN));
    index += SIZE_OF_LONG;
    assertEquals(leadershipTermId, logBuffer.getLong(index, LITTLE_ENDIAN));
    index += SIZE_OF_LONG;
    assertEquals(logPosition, logBuffer.getLong(index, LITTLE_ENDIAN));
    index += SIZE_OF_LONG;
    assertEquals(logLeadershipTermId, logBuffer.getLong(index, LITTLE_ENDIAN));
    index += SIZE_OF_LONG;
    assertEquals(appendPosition, logBuffer.getLong(index, LITTLE_ENDIAN));
    index += SIZE_OF_LONG;
    assertEquals(catchupPosition, logBuffer.getLong(index, LITTLE_ENDIAN));
    index += SIZE_OF_LONG;
    assertEquals(from.name() + STATE_SEPARATOR + "null", logBuffer.getStringAscii(index));
}
Also used : ChronoUnit(java.time.temporal.ChronoUnit) Test(org.junit.jupiter.api.Test)

Example 14 with ChronoUnit

use of java.time.temporal.ChronoUnit in project Aeron by real-logic.

the class ArchiveEventLoggerTest method logSessionStateChange.

@Test
void logSessionStateChange() {
    final int offset = ALIGNMENT * 4;
    logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, offset);
    final ChronoUnit from = ChronoUnit.CENTURIES;
    final ChronoUnit to = ChronoUnit.MICROS;
    final long id = 555_000_000_000L;
    final String payload = from.name() + STATE_SEPARATOR + to.name();
    final int captureLength = SIZE_OF_LONG + SIZE_OF_INT + payload.length();
    logger.logSessionStateChange(CONTROL_SESSION_STATE_CHANGE, from, to, id);
    verifyLogHeader(logBuffer, offset, CONTROL_SESSION_STATE_CHANGE.toEventCodeId(), captureLength, captureLength);
    assertEquals(id, logBuffer.getLong(encodedMsgOffset(offset + LOG_HEADER_LENGTH), LITTLE_ENDIAN));
    assertEquals(payload, logBuffer.getStringAscii(encodedMsgOffset(offset + LOG_HEADER_LENGTH + SIZE_OF_LONG)));
}
Also used : ChronoUnit(java.time.temporal.ChronoUnit) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 15 with ChronoUnit

use of java.time.temporal.ChronoUnit in project hippo by NHS-digital-website.

the class CmsSteps method givenIHaveAPublishedPublicationWithNominalDateFallingBeforeWeeksFromNow.

@Given("^I have a published publication with nominal date falling before (-?\\d+) (days|weeks|years) from now$")
public void givenIHaveAPublishedPublicationWithNominalDateFallingBeforeWeeksFromNow(final int valueFromNow, final String unit) throws Throwable {
    ChronoUnit chronoUnit = ChronoUnit.valueOf(unit.toUpperCase());
    final Publication publicationWithNominalDateBeforeCutOff = TestDataFactory.createBareMinimumPublication().withNominalDate(LocalDateTime.now().plus(valueFromNow, chronoUnit).toInstant(ZoneOffset.UTC)).build();
    testDataRepo.setPublication(publicationWithNominalDateBeforeCutOff);
    createPublishedPublication(publicationWithNominalDateBeforeCutOff);
}
Also used : Publication(uk.nhs.digital.ps.test.acceptance.models.Publication) ChronoUnit(java.time.temporal.ChronoUnit) Given(cucumber.api.java.en.Given)

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