org.threeten.bp.temporal.TemporalAccessor Java Examples

The following examples show how to use org.threeten.bp.temporal.TemporalAccessor. 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: TestDateTimeFormatters.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test(dataProvider="sample_isoOffsetDateTime")
public void test_print_isoOffsetDateTime(
        Integer year, Integer month, Integer day,
        Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId,
        String expected, Class<?> expectedEx) {
    TemporalAccessor test = buildAccessor(year, month, day, hour, min, sec, nano, offsetId, zoneId);
    if (expectedEx == null) {
        assertEquals(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(test), expected);
    } else {
        try {
            DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(test);
            fail();
        } catch (Exception ex) {
            assertTrue(expectedEx.isInstance(ex));
        }
    }
}
 
Example #2
Source File: TestDateTimeFormatters.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test(dataProvider="sample_isoOffsetTime")
public void test_print_isoOffsetTime(
        Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId,
        String expected, Class<?> expectedEx) {
    TemporalAccessor test = buildAccessor(null, null, null, hour, min, sec, nano, offsetId, zoneId);
    if (expectedEx == null) {
        assertEquals(DateTimeFormatter.ISO_OFFSET_TIME.format(test), expected);
    } else {
        try {
            DateTimeFormatter.ISO_OFFSET_TIME.format(test);
            fail();
        } catch (Exception ex) {
            assertTrue(expectedEx.isInstance(ex));
        }
    }
}
 
Example #3
Source File: TestDateTimeFormatters.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test(dataProvider="sample_isoOffsetDate")
public void test_print_isoOffsetDate(
        Integer year, Integer month, Integer day, String offsetId, String zoneId,
        String expected, Class<?> expectedEx) {
    TemporalAccessor test = buildAccessor(year, month, day, null, null, null, null, offsetId, zoneId);
    if (expectedEx == null) {
        assertEquals(DateTimeFormatter.ISO_OFFSET_DATE.format(test), expected);
    } else {
        try {
            DateTimeFormatter.ISO_OFFSET_DATE.format(test);
            fail();
        } catch (Exception ex) {
            assertTrue(expectedEx.isInstance(ex));
        }
    }
}
 
Example #4
Source File: Chronology.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Obtains a zoned date-time in this chronology from another temporal object.
 * <p>
 * This creates a date-time in this chronology based on the specified {@code TemporalAccessor}.
 * <p>
 * This should obtain a {@code ZoneId} using {@link ZoneId#from(TemporalAccessor)}.
 * The date-time should be obtained by obtaining an {@code Instant}.
 * If that fails, the local date-time should be used.
 *
 * @param temporal  the temporal object to convert, not null
 * @return the zoned date-time in this chronology, not null
 * @throws DateTimeException if unable to create the date-time
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public ChronoZonedDateTime<?> zonedDateTime(TemporalAccessor temporal) {
    try {
        ZoneId zone = ZoneId.from(temporal);
        try {
            Instant instant = Instant.from(temporal);
            return zonedDateTime(instant, zone);

        } catch (DateTimeException ex1) {
            ChronoLocalDateTime cldt = localDateTime(temporal);
            ChronoLocalDateTimeImpl cldtImpl = ensureChronoLocalDateTime(cldt);
            return ChronoZonedDateTimeImpl.ofBest(cldtImpl, zone, null);
        }
    } catch (DateTimeException ex) {
        throw new DateTimeException("Unable to obtain ChronoZonedDateTime from TemporalAccessor: " + temporal.getClass(), ex);
    }
}
 
Example #5
Source File: LocalDateTime.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Obtains an instance of {@code LocalDateTime} from a temporal object.
 * <p>
 * A {@code TemporalAccessor} represents some form of date and time information.
 * This factory converts the arbitrary temporal object to an instance of {@code LocalDateTime}.
 * <p>
 * The conversion extracts and combines {@code LocalDate} and {@code LocalTime}.
 * <p>
 * This method matches the signature of the functional interface {@link TemporalQuery}
 * allowing it to be used as a query via method reference, {@code LocalDateTime::from}.
 *
 * @param temporal  the temporal object to convert, not null
 * @return the local date-time, not null
 * @throws DateTimeException if unable to convert to a {@code LocalDateTime}
 */
public static LocalDateTime from(TemporalAccessor temporal) {
    if (temporal instanceof LocalDateTime) {
        return (LocalDateTime) temporal;
    } else if (temporal instanceof ZonedDateTime) {
        return ((ZonedDateTime) temporal).toLocalDateTime();
    }
    try {
        LocalDate date = LocalDate.from(temporal);
        LocalTime time = LocalTime.from(temporal);
        return new LocalDateTime(date, time);
    } catch (DateTimeException ex) {
        throw new DateTimeException("Unable to obtain LocalDateTime from TemporalAccessor: " +
                temporal + ", type " + temporal.getClass().getName());
    }
}
 
Example #6
Source File: DateTimeBuilder.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void crossCheck(TemporalAccessor temporal) {
    Iterator<Entry<TemporalField, Long>> it = fieldValues.entrySet().iterator();
    while (it.hasNext()) {
        Entry<TemporalField, Long> entry = it.next();
        TemporalField field = entry.getKey();
        long value = entry.getValue();
        if (temporal.isSupported(field)) {
            long temporalValue;
            try {
                temporalValue = temporal.getLong(field);
            } catch (RuntimeException ex) {
                continue;
            }
            if (temporalValue != value) {
                throw new DateTimeException("Cross check failed: " +
                        field + " " + temporalValue + " vs " + field + " " + value);
            }
            it.remove();
        }
    }
}
 
Example #7
Source File: TestDateTimeFormatters.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test(dataProvider="sample_isoDate")
public void test_print_isoDate(
        Integer year, Integer month, Integer day, String offsetId, String zoneId,
        String expected, Class<?> expectedEx) {
    TemporalAccessor test = buildAccessor(year, month, day, null, null, null, null, offsetId, zoneId);
    if (expectedEx == null) {
        assertEquals(DateTimeFormatter.ISO_DATE.format(test), expected);
    } else {
        try {
            DateTimeFormatter.ISO_DATE.format(test);
            fail();
        } catch (Exception ex) {
            assertTrue(expectedEx.isInstance(ex));
        }
    }
}
 
Example #8
Source File: CustomInstantDeserializer.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
protected CustomInstantDeserializer(Class<T> supportedType,
                  DateTimeFormatter parser,
                  Function<TemporalAccessor, T> parsedToValue,
                  Function<FromIntegerArguments, T> fromMilliseconds,
                  Function<FromDecimalArguments, T> fromNanoseconds,
                  BiFunction<T, ZoneId, T> adjust) {
  super(supportedType, parser);
  this.parsedToValue = parsedToValue;
  this.fromMilliseconds = fromMilliseconds;
  this.fromNanoseconds = fromNanoseconds;
  this.adjust = adjust == null ? new BiFunction<T, ZoneId, T>() {
    @Override
    public T apply(T t, ZoneId zoneId) {
      return t;
    }
  } : adjust;
}
 
Example #9
Source File: CustomInstantDeserializer.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
protected CustomInstantDeserializer(Class<T> supportedType,
                  DateTimeFormatter parser,
                  Function<TemporalAccessor, T> parsedToValue,
                  Function<FromIntegerArguments, T> fromMilliseconds,
                  Function<FromDecimalArguments, T> fromNanoseconds,
                  BiFunction<T, ZoneId, T> adjust) {
  super(supportedType, parser);
  this.parsedToValue = parsedToValue;
  this.fromMilliseconds = fromMilliseconds;
  this.fromNanoseconds = fromNanoseconds;
  this.adjust = adjust == null ? new BiFunction<T, ZoneId, T>() {
    @Override
    public T apply(T t, ZoneId zoneId) {
      return t;
    }
  } : adjust;
}
 
Example #10
Source File: TestDateTimeFormatters.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test(dataProvider="sample_isoTime")
public void test_print_isoTime(
        Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId,
        String expected, Class<?> expectedEx) {
    TemporalAccessor test = buildAccessor(null, null, null, hour, min, sec, nano, offsetId, zoneId);
    if (expectedEx == null) {
        assertEquals(DateTimeFormatter.ISO_TIME.format(test), expected);
    } else {
        try {
            DateTimeFormatter.ISO_TIME.format(test);
            fail();
        } catch (Exception ex) {
            assertTrue(expectedEx.isInstance(ex));
        }
    }
}
 
Example #11
Source File: UsabilityBasic.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static void lookup() {
        LocalDate date = LocalDate.now();
        LocalTime time = LocalTime.now();
        LocalDateTime dateTime = LocalDateTime.now();
//        System.out.println(LocalDateField.DAY_OF_MONTH.getDateRules().get(date));
//        System.out.println(LocalDateField.MONTH_OF_YEAR.getDateRules().get(date));
//        System.out.println(LocalDateField.YEAR.getDateRules().get(date));
//        System.out.println(QuarterYearField.QUARTER_OF_YEAR.getDateRules().get(date));
//        System.out.println(QuarterYearField.MONTH_OF_QUARTER.getDateRules().get(date));
//        System.out.println(QuarterYearField.DAY_OF_QUARTER.getDateRules().get(date));

        output(date, ChronoField.DAY_OF_MONTH);
        output(date, ChronoField.MONTH_OF_YEAR);
        output(date, ChronoField.YEAR);

        output(dateTime, ChronoField.DAY_OF_MONTH);
        output(time, ChronoField.HOUR_OF_DAY);
        output(time, ChronoField.MINUTE_OF_HOUR);

        TemporalAccessor cal = date;
        System.out.println("DoM: " + cal.get(DAY_OF_MONTH));
    }
 
Example #12
Source File: TestDateTimeParsing.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void test_parse_fromField_InstantSeconds() {
    DateTimeFormatter fmt = new DateTimeFormatterBuilder()
        .appendValue(INSTANT_SECONDS).toFormatter();
    TemporalAccessor acc = fmt.parse("86402");
    Instant expected = Instant.ofEpochSecond(86402);
    assertEquals(acc.isSupported(INSTANT_SECONDS), true);
    assertEquals(acc.isSupported(NANO_OF_SECOND), true);
    assertEquals(acc.isSupported(MICRO_OF_SECOND), true);
    assertEquals(acc.isSupported(MILLI_OF_SECOND), true);
    assertEquals(acc.getLong(INSTANT_SECONDS), 86402L);
    assertEquals(acc.getLong(NANO_OF_SECOND), 0L);
    assertEquals(acc.getLong(MICRO_OF_SECOND), 0L);
    assertEquals(acc.getLong(MILLI_OF_SECOND), 0L);
    assertEquals(Instant.from(acc), expected);
}
 
Example #13
Source File: TestDateTimeFormatters.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test(dataProvider="sample_isoLocalDate")
public void test_print_isoLocalDate(
        Integer year, Integer month, Integer day, String offsetId, String zoneId,
        String expected, Class<?> expectedEx) {
    TemporalAccessor test = buildAccessor(year, month, day, null, null, null, null, offsetId, zoneId);
    if (expectedEx == null) {
        assertEquals(DateTimeFormatter.ISO_LOCAL_DATE.format(test), expected);
    } else {
        try {
            DateTimeFormatter.ISO_LOCAL_DATE.format(test);
            fail();
        } catch (Exception ex) {
            assertTrue(expectedEx.isInstance(ex));
        }
    }
}
 
Example #14
Source File: TestDateTimeFormatters.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test(dataProvider="sample_isoZonedDateTime")
public void test_print_isoZonedDateTime(
        Integer year, Integer month, Integer day,
        Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId,
        String expected, Class<?> expectedEx) {
    TemporalAccessor test = buildAccessor(year, month, day, hour, min, sec, nano, offsetId, zoneId);
    if (expectedEx == null) {
        assertEquals(DateTimeFormatter.ISO_ZONED_DATE_TIME.format(test), expected);
    } else {
        try {
            DateTimeFormatter.ISO_ZONED_DATE_TIME.format(test);
            fail(test.toString());
        } catch (Exception ex) {
            assertTrue(expectedEx.isInstance(ex));
        }
    }
}
 
Example #15
Source File: CustomInstantDeserializer.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
protected CustomInstantDeserializer(Class<T> supportedType,
                  DateTimeFormatter parser,
                  Function<TemporalAccessor, T> parsedToValue,
                  Function<FromIntegerArguments, T> fromMilliseconds,
                  Function<FromDecimalArguments, T> fromNanoseconds,
                  BiFunction<T, ZoneId, T> adjust) {
  super(supportedType, parser);
  this.parsedToValue = parsedToValue;
  this.fromMilliseconds = fromMilliseconds;
  this.fromNanoseconds = fromNanoseconds;
  this.adjust = adjust == null ? new BiFunction<T, ZoneId, T>() {
    @Override
    public T apply(T t, ZoneId zoneId) {
      return t;
    }
  } : adjust;
}
 
Example #16
Source File: CustomInstantDeserializer.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
protected CustomInstantDeserializer(Class<T> supportedType,
                  DateTimeFormatter parser,
                  Function<TemporalAccessor, T> parsedToValue,
                  Function<FromIntegerArguments, T> fromMilliseconds,
                  Function<FromDecimalArguments, T> fromNanoseconds,
                  BiFunction<T, ZoneId, T> adjust) {
  super(supportedType, parser);
  this.parsedToValue = parsedToValue;
  this.fromMilliseconds = fromMilliseconds;
  this.fromNanoseconds = fromNanoseconds;
  this.adjust = adjust == null ? new BiFunction<T, ZoneId, T>() {
    @Override
    public T apply(T t, ZoneId zoneId) {
      return t;
    }
  } : adjust;
}
 
Example #17
Source File: DateTimeFormatter.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Boolean queryFrom(TemporalAccessor temporal) {
    if (temporal instanceof DateTimeBuilder) {
        return ((DateTimeBuilder) temporal).leapSecond;
    } else {
        return Boolean.FALSE;
    }
}
 
Example #18
Source File: TestDateTimeFormatters.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void assertParseMatch(TemporalAccessor parsed, Expected expected) {
    for (TemporalField field : expected.fieldValues.keySet()) {
        assertEquals(parsed.isSupported(field), true);
        parsed.getLong(field);
    }
    assertEquals(parsed.query(TemporalQueries.chronology()), expected.chrono);
    assertEquals(parsed.query(TemporalQueries.zoneId()), expected.zone);
}
 
Example #19
Source File: AbstractDateTimeTest.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void basicTest_query() {
    for (TemporalAccessor sample : samples()) {
        assertEquals(sample.query(new TemporalQuery<String>() {
            @Override
            public String queryFrom(TemporalAccessor dateTime) {
                return "foo";
            }
        }), "foo");
    }
}
 
Example #20
Source File: TestDateTimeFormatterBuilder.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void test_appendValueReduced_subsequent_parse() throws Exception {
    builder.appendValue(MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL).appendValueReduced(YEAR, 2, 2, 2000);
    DateTimeFormatter f = builder.toFormatter();
    assertEquals(f.toString(), "Value(MonthOfYear,1,2,NORMAL)ReducedValue(Year,2,2,2000)");
    TemporalAccessor cal = f.parseUnresolved("123", new ParsePosition(0));
    assertEquals(cal.get(MONTH_OF_YEAR), 1);
    assertEquals(cal.get(YEAR), 2023);
}
 
Example #21
Source File: AbstractDateTimeTest.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void basicTest_isSupported_DateTimeField_unsupported() {
    for (TemporalAccessor sample : samples()) {
        for (TemporalField field : invalidFields()) {
            assertEquals(sample.isSupported(field), false, "Failed on " + sample + " " + field);
        }
    }
}
 
Example #22
Source File: HijrahChronology.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override  // override with covariant return type
public HijrahDate date(TemporalAccessor temporal) {
    if (temporal instanceof HijrahDate) {
        return (HijrahDate) temporal;
    }
    return HijrahDate.ofEpochDay(temporal.getLong(EPOCH_DAY));
}
 
Example #23
Source File: TestDateTimeParsing.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void test_parse_fromField_SecondOfMinute() {
    DateTimeFormatter fmt = new DateTimeFormatterBuilder()
        .appendValue(SECOND_OF_MINUTE).toFormatter();
    TemporalAccessor acc = fmt.parse("32");
    assertEquals(acc.isSupported(SECOND_OF_MINUTE), true);
    assertEquals(acc.isSupported(NANO_OF_SECOND), true);
    assertEquals(acc.isSupported(MICRO_OF_SECOND), true);
    assertEquals(acc.isSupported(MILLI_OF_SECOND), true);
    assertEquals(acc.getLong(SECOND_OF_MINUTE), 32L);
    assertEquals(acc.getLong(NANO_OF_SECOND), 0L);
    assertEquals(acc.getLong(MICRO_OF_SECOND), 0L);
    assertEquals(acc.getLong(MILLI_OF_SECOND), 0L);
}
 
Example #24
Source File: ThaiBuddhistChronology.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override  // override with covariant return type
public ThaiBuddhistDate date(TemporalAccessor temporal) {
    if (temporal instanceof ThaiBuddhistDate) {
        return (ThaiBuddhistDate) temporal;
    }
    return new ThaiBuddhistDate(LocalDate.from(temporal));
}
 
Example #25
Source File: TestDateTimeFormatters.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void test_parse_weekDate_largeYear() {
    TemporalAccessor parsed = DateTimeFormatter.ISO_WEEK_DATE.parseUnresolved("+123456-W04-5", new ParsePosition(0));
    assertEquals(parsed.get(IsoFields.WEEK_BASED_YEAR), 123456);
    assertEquals(parsed.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR), 4);
    assertEquals(parsed.get(DAY_OF_WEEK), 5);
}
 
Example #26
Source File: CustomInstantDeserializer.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public Instant apply(TemporalAccessor temporalAccessor) {
  return Instant.from(temporalAccessor);
}
 
Example #27
Source File: CustomInstantDeserializer.java    From tutorials with MIT License 4 votes vote down vote up
@Override
public ZonedDateTime apply(TemporalAccessor temporalAccessor) {
  return ZonedDateTime.from(temporalAccessor);
}
 
Example #28
Source File: TestInstant.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected List<TemporalAccessor> samples() {
    TemporalAccessor[] array = {TEST_12345_123456789, Instant.MIN, Instant.MAX, Instant.EPOCH};
    return Arrays.asList(array);
}
 
Example #29
Source File: TestDateTimeFormatters.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void test_print_isoOrdinalDate() {
    TemporalAccessor test = buildAccessor(LocalDateTime.of(2008, 6, 3, 11, 5, 30), null, null);
    assertEquals(DateTimeFormatter.ISO_ORDINAL_DATE.format(test), "2008-155");
}
 
Example #30
Source File: OffsetTime.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public OffsetTime queryFrom(TemporalAccessor temporal) {
    return OffsetTime.from(temporal);
}