java.time.temporal.Temporal Java Examples

The following examples show how to use java.time.temporal.Temporal. 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: JsonNodeMappingSupport.java    From shimmer with Apache License 2.0 6 votes vote down vote up
/**
 * @param parentNode a parent node
 * @param path the path to a child node
 * @param formatter the formatter to use to parse the value of the child node
 * @param parseFunction the function to use to parse the value
 * @param <T> the generic temporal type
 * @return the value of the child node as an instance of the temporal type, or an empty optional if the child
 * doesn't exist or if the value of the child node isn't parseable
 */
public static <T extends Temporal> Optional<T> asOptionalTemporal(
        JsonNode parentNode,
        String path,
        DateTimeFormatter formatter,
        BiFunction<String, DateTimeFormatter, T> parseFunction) {

    Optional<String> string = asOptionalString(parentNode, path);

    if (!string.isPresent()) {
        return empty();
    }

    T temporal = null;

    try {
        temporal = parseFunction.apply(string.get(), formatter);
    }
    catch (DateTimeParseException e) {
        logger.warn("The '{}' field in node '{}' with value '{}' isn't a valid temporal.",
                path, parentNode, string.get(), e);
    }

    return Optional.ofNullable(temporal);
}
 
Example #2
Source File: ChronoLocalDateImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Override
public long until(Temporal endExclusive, TemporalUnit unit) {
    Objects.requireNonNull(endExclusive, "endExclusive");
    ChronoLocalDate end = getChronology().date(endExclusive);
    if (unit instanceof ChronoUnit) {
        switch ((ChronoUnit) unit) {
            case DAYS: return daysUntil(end);
            case WEEKS: return daysUntil(end) / 7;
            case MONTHS: return monthsUntil(end);
            case YEARS: return monthsUntil(end) / 12;
            case DECADES: return monthsUntil(end) / 120;
            case CENTURIES: return monthsUntil(end) / 1200;
            case MILLENNIA: return monthsUntil(end) / 12000;
            case ERAS: return end.getLong(ERA) - getLong(ERA);
        }
        throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
    }
    Objects.requireNonNull(unit, "unit");
    return unit.between(this, end);
}
 
Example #3
Source File: ChronoPeriodImpl.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Temporal addTo(Temporal temporal) {
    validateChrono(temporal);
    if (months == 0) {
        if (years != 0) {
            temporal = temporal.plus(years, YEARS);
        }
    } else {
        long monthRange = monthRange();
        if (monthRange > 0) {
            temporal = temporal.plus(years * monthRange + months, MONTHS);
        } else {
            if (years != 0) {
                temporal = temporal.plus(years, YEARS);
            }
            temporal = temporal.plus(months, MONTHS);
        }
    }
    if (days != 0) {
        temporal = temporal.plus(days, DAYS);
    }
    return temporal;
}
 
Example #4
Source File: NormalizeDateTimeLiteralsTransformer.java    From jdmn with Apache License 2.0 6 votes vote down vote up
private String normalizeLiteral(String feelFunctionName, String literalText) {
    try {
        Temporal temporal;
        String rawText = literalText.replaceAll("\"", "");
        if ("date and time".equals(feelFunctionName)) {
            // date and time
            temporal = this.feelLib.dateAndTime(rawText).withZoneSameInstant(ZoneOffset.UTC);
        } else {
            // time
            temporal = this.feelLib.time(rawText).withOffsetSameInstant(ZoneOffset.UTC);
        }
        return String.format("\"%s\"", this.feelLib.string(temporal));
    } catch (Exception e) {
        return literalText;
    }
}
 
Example #5
Source File: FHIRPathUtil.java    From FHIR with Apache License 2.0 6 votes vote down vote up
public static TemporalAccessor getTemporalAccessor(Temporal temporal, Class<?> targetType) {
    if (temporal.getClass().equals(targetType)) {
        return temporal;
    }
    if (Year.class.equals(targetType)) {
        return Year.from(temporal);
    } else if (YearMonth.class.equals(targetType)) {
        return YearMonth.from(temporal);
    } else if (LocalDate.class.equals(targetType)) {
        return LocalDate.from(temporal);
    } else if (LocalDateTime.class.equals(targetType)) {
        return LocalDateTime.from(temporal);
    } else if (ZonedDateTime.class.equals(targetType)){
        return ZonedDateTime.from(temporal);
    } else if (LocalTime.class.equals(targetType)) {
        return LocalTime.from(temporal);
    }
    throw new IllegalArgumentException();
}
 
Example #6
Source File: TCKYear.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_adjustDate() {
    LocalDate base = LocalDate.of(2007, 2, 12);
    for (int i = -4; i <= 2104; i++) {
        Temporal result = Year.of(i).adjustInto(base);
        assertEquals(result, LocalDate.of(i, 2, 12));
    }
}
 
Example #7
Source File: ChronoLocalDateTimeImpl.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
@Override
public long until(Temporal endExclusive, TemporalUnit unit) {
    Objects.requireNonNull(endExclusive, "endExclusive");
    @SuppressWarnings("unchecked")
    ChronoLocalDateTime<D> end = (ChronoLocalDateTime<D>) getChronology().localDateTime(endExclusive);
    if (unit instanceof ChronoUnit) {
        if (unit.isTimeBased()) {
            long amount = end.getLong(EPOCH_DAY) - date.getLong(EPOCH_DAY);
            switch ((ChronoUnit) unit) {
                case NANOS: amount = Math.multiplyExact(amount, NANOS_PER_DAY); break;
                case MICROS: amount = Math.multiplyExact(amount, MICROS_PER_DAY); break;
                case MILLIS: amount = Math.multiplyExact(amount, MILLIS_PER_DAY); break;
                case SECONDS: amount = Math.multiplyExact(amount, SECONDS_PER_DAY); break;
                case MINUTES: amount = Math.multiplyExact(amount, MINUTES_PER_DAY); break;
                case HOURS: amount = Math.multiplyExact(amount, HOURS_PER_DAY); break;
                case HALF_DAYS: amount = Math.multiplyExact(amount, 2); break;
            }
            return Math.addExact(amount, time.until(end.toLocalTime(), unit));
        }
        ChronoLocalDate endDate = end.toLocalDate();
        if (end.toLocalTime().isBefore(time)) {
            endDate = endDate.minus(1, ChronoUnit.DAYS);
        }
        return date.until(endDate, unit);
    }
    Objects.requireNonNull(unit, "unit");
    return unit.between(this, end);
}
 
Example #8
Source File: TCKOffsetTime.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_with_adjustment_AmPm() {
    OffsetTime test = TEST_11_30_59_500_PONE.with(new TemporalAdjuster() {
        @Override
        public Temporal adjustInto(Temporal dateTime) {
            return dateTime.with(HOUR_OF_DAY, 23);
        }
    });
    assertEquals(test, OffsetTime.of(23, 30, 59, 500, OFFSET_PONE));
}
 
Example #9
Source File: GamaDate.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public static GamaDate fromISOString(final String s) {
	try {
		final TemporalAccessor t = Dates.getFormatter(Dates.ISO_OFFSET_KEY, null).parse(s);
		if (t instanceof Temporal) { return of((Temporal) t); }
	} catch (final DateTimeParseException e) {}
	return new GamaDate(null, s);
}
 
Example #10
Source File: TCKChronoPeriod.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="calendars")
public void test_addTo(Chronology chrono) {
    ChronoPeriod period = chrono.period(1, 2, 3);
    ChronoLocalDate date = chrono.dateNow();
    Temporal result = period.addTo(date);
    assertEquals(result, date.plus(14, MONTHS).plus(3, DAYS));
}
 
Example #11
Source File: TCKFormatStyle.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("data_formatStyle")
public void test_formatStyle(Temporal temporal, FormatStyle style, String formattedStr) {
    DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
    DateTimeFormatter formatter = builder.appendLocalized(style, style).appendLiteral(" ").appendZoneOrOffsetId().toFormatter();
    // Android-changed: Use a locale that actually uses "CEST" as short form of Europe/Paris.
    formatter = formatter.withLocale(Locale.UK);
    assertEquals(formatter.format(temporal), formattedStr);
}
 
Example #12
Source File: TCKOffsetTime.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_with_adjustment() {
    final OffsetTime sample = OffsetTime.of(23, 5, 0, 0, OFFSET_PONE);
    TemporalAdjuster adjuster = new TemporalAdjuster() {
        @Override
        public Temporal adjustInto(Temporal dateTime) {
            return sample;
        }
    };
    assertEquals(TEST_11_30_59_500_PONE.with(adjuster), sample);
}
 
Example #13
Source File: ChronoLocalDateTimeImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a copy of this date-time with the new date and time, checking
 * to see if a new object is in fact required.
 *
 * @param newDate  the date of the new date-time, not null
 * @param newTime  the time of the new date-time, not null
 * @return the date-time, not null
 */
private ChronoLocalDateTimeImpl<D> with(Temporal newDate, LocalTime newTime) {
    if (date == newDate && time == newTime) {
        return this;
    }
    // Validate that the new Temporal is a ChronoLocalDate (and not something else)
    D cd = ChronoLocalDateImpl.ensureValid(date.getChronology(), newDate);
    return new ChronoLocalDateTimeImpl<>(cd, newTime);
}
 
Example #14
Source File: ChronoLocalDateTimeImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Casts the {@code Temporal} to {@code ChronoLocalDateTime} ensuring it bas the specified chronology.
 *
 * @param chrono  the chronology to check for, not null
 * @param temporal   a date-time to cast, not null
 * @return the date-time checked and cast to {@code ChronoLocalDateTime}, not null
 * @throws ClassCastException if the date-time cannot be cast to ChronoLocalDateTimeImpl
 *  or the chronology is not equal this Chronology
 */
static <R extends ChronoLocalDate> ChronoLocalDateTimeImpl<R> ensureValid(Chronology chrono, Temporal temporal) {
    @SuppressWarnings("unchecked")
    ChronoLocalDateTimeImpl<R> other = (ChronoLocalDateTimeImpl<R>) temporal;
    if (chrono.equals(other.getChronology()) == false) {
        throw new ClassCastException("Chronology mismatch, required: " + chrono.getId()
                + ", actual: " + other.getChronology().getId());
    }
    return other;
}
 
Example #15
Source File: TCKFormatStyle.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "formatStyle")
public void test_formatStyle(Temporal temporal, FormatStyle style, String formattedStr) {
    DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
    DateTimeFormatter formatter = builder.appendLocalized(style, style).appendLiteral(" ").appendZoneOrOffsetId().toFormatter();
    formatter = formatter.withLocale(Locale.US);
    assertEquals(formatter.format(temporal), formattedStr);
}
 
Example #16
Source File: TimePeriod.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Temporal subtractFrom(Temporal temporal) {
    for(Map.Entry<TemporalUnit, Long> entry : values.entrySet()) {
        temporal = temporal.minus(entry.getValue(), entry.getKey());
    }
    return temporal;
}
 
Example #17
Source File: ChronoLocalDateTimeImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a copy of this date-time with the new date and time, checking
 * to see if a new object is in fact required.
 *
 * @param newDate  the date of the new date-time, not null
 * @param newTime  the time of the new date-time, not null
 * @return the date-time, not null
 */
private ChronoLocalDateTimeImpl<D> with(Temporal newDate, LocalTime newTime) {
    if (date == newDate && time == newTime) {
        return this;
    }
    // Validate that the new Temporal is a ChronoLocalDate (and not something else)
    D cd = ChronoLocalDateImpl.ensureValid(date.getChronology(), newDate);
    return new ChronoLocalDateTimeImpl<>(cd, newTime);
}
 
Example #18
Source File: TCKOffsetDateTime.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_with_adjustment() {
    final OffsetDateTime sample = OffsetDateTime.of(LocalDate.of(2012, 3, 4), LocalTime.of(23, 5), OFFSET_PONE);
    TemporalAdjuster adjuster = new TemporalAdjuster() {
        @Override
        public Temporal adjustInto(Temporal dateTime) {
            return sample;
        }
    };
    assertEquals(TEST_2008_6_30_11_30_59_000000500.with(adjuster), sample);
}
 
Example #19
Source File: DateTransformer.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
@Override
public Temporal in(final String o) {
    TemporalQuery<?> temporalAccessor = TEMPORAL_QUERYS.get(targetClassName);

    if (temporalAccessor == null || dateTimeFormatter == null) {
        throw msg.notValidDateOrTimeType(targetClassName);
    }

    return (Temporal) dateTimeFormatter.parse(o.toString(), temporalAccessor);
}
 
Example #20
Source File: TCKChronoPeriod.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="calendars")
public void test_addTo(Chronology chrono) {
    ChronoPeriod period = chrono.period(1, 2, 3);
    ChronoLocalDate date = chrono.dateNow();
    Temporal result = period.addTo(date);
    assertEquals(result, date.plus(14, MONTHS).plus(3, DAYS));
}
 
Example #21
Source File: ChronoLocalDateTimeImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Casts the {@code Temporal} to {@code ChronoLocalDateTime} ensuring it bas the specified chronology.
 *
 * @param chrono  the chronology to check for, not null
 * @param temporal   a date-time to cast, not null
 * @return the date-time checked and cast to {@code ChronoLocalDateTime}, not null
 * @throws ClassCastException if the date-time cannot be cast to ChronoLocalDateTimeImpl
 *  or the chronology is not equal this Chronology
 */
static <R extends ChronoLocalDate> ChronoLocalDateTimeImpl<R> ensureValid(Chronology chrono, Temporal temporal) {
    @SuppressWarnings("unchecked")
    ChronoLocalDateTimeImpl<R> other = (ChronoLocalDateTimeImpl<R>) temporal;
    if (chrono.equals(other.getChronology()) == false) {
        throw new ClassCastException("Chronology mismatch, required: " + chrono.getId()
                + ", actual: " + other.getChronology().getId());
    }
    return other;
}
 
Example #22
Source File: TestDateTimeFormatterBuilder.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider="patternPrint")
public void test_appendPattern_patternPrint(String input, Temporal temporal, String expected) throws Exception {
    DateTimeFormatter f = builder.appendPattern(input).toFormatter(Locale.UK);
    String test = f.format(temporal);
    assertEquals(test, expected);
}
 
Example #23
Source File: TCKInstant.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public long between(Temporal temporal1, Temporal temporal2) {
    throw new UnsupportedOperationException();
}
 
Example #24
Source File: TCKChronoLocalDateTime.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <R extends Temporal> R adjustInto(R temporal, long newValue) {
    return (R) this.temporal;
}
 
Example #25
Source File: TCKChronoLocalDate.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <R extends Temporal> R adjustInto(R temporal, long newValue) {
    return (R) this.temporal;
}
 
Example #26
Source File: TCKChronoLocalDate.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Temporal addTo(Temporal ignore) {
    return datetime;
}
 
Example #27
Source File: PureJavaTimeDMNDialectDefinition.java    From jdmn with Apache License 2.0 4 votes vote down vote up
@Override
public FEELLib<BigDecimal, LocalDate, Temporal, Temporal, TemporalAmount> createFEELLib() {
    return new PureJavaTimeFEELLib();
}
 
Example #28
Source File: TCKChronoLocalDateTime.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
FixedTemporalUnit(Temporal temporal) {
    this.temporal = temporal;
}
 
Example #29
Source File: TCKChronoZonedDateTime.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
@Override
public boolean isSupportedBy(Temporal temporal) {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example #30
Source File: TCKDayOfWeek.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void test_adjustInto_null() {
    DayOfWeek.MONDAY.adjustInto((Temporal) null);
}