/** * Obtains an instance of {@code OffsetDateTime} from a date-time object. * <p> * A {@code DateTimeAccessor} represents some form of date and time information. This factory converts the * arbitrary date-time object to an instance of {@code OffsetDateTime}. * * @param dateTime the date-time object to convert, not null * @return the offset date-time, not null * @throws DateTimeException if unable to convert to an {@code OffsetDateTime} */ public static OffsetDateTime from(DateTimeAccessor dateTime) { if (dateTime instanceof OffsetDateTime) { return (OffsetDateTime) dateTime; } ZoneOffset offset = ZoneOffset.from(dateTime); try { try { LocalDateTime ldt = LocalDateTime.from(dateTime); return OffsetDateTime.of(ldt, offset); } catch (DateTimeException ignore) { Instant instant = Instant.from(dateTime); return OffsetDateTime.ofInstant(instant, offset); } } catch (DateTimeException ex) { throw new DateTimeException("Unable to convert DateTimeAccessor to OffsetDateTime: " + dateTime.getClass(), ex); } }
/** * Obtains an instance of {@code LocalTime} from a date-time object. * <p> * A {@code DateTimeAccessor} represents some form of date and time information. This factory converts the * arbitrary date-time object to an instance of {@code LocalTime}. * <p> * The conversion extracts the {@link ChronoField#NANO_OF_DAY nano-of-day} field. * * @param dateTime the date-time object to convert, not null * @return the local time, not null * @throws DateTimeException if unable to convert to a {@code LocalTime} */ public static LocalTime from(DateTimeAccessor dateTime) { if (dateTime instanceof LocalTime) { return (LocalTime) dateTime; } else if (dateTime instanceof ChronoLocalDateTime) { return ((ChronoLocalDateTime<?>) dateTime).getTime(); } else if (dateTime instanceof ZonedDateTime) { return ((ChronoZonedDateTime<?>) dateTime).getTime(); } // handle builder as a special case if (dateTime instanceof DateTimeBuilder) { DateTimeBuilder builder = (DateTimeBuilder) dateTime; LocalTime time = builder.extract(LocalTime.class); if (time != null) { return time; } } return ofNanoOfDay(dateTime.getLong(NANO_OF_DAY)); }
/** * Obtains an instance of {@code LocalDate} from a date-time object. * <p> * A {@code DateTimeAccessor} represents some form of date and time information. This factory converts the * arbitrary date-time object to an instance of {@code LocalDate}. * <p> * The conversion extracts the {@link ChronoField#EPOCH_DAY epoch-day} field. * * @param dateTime the date-time object to convert, not null * @return the local date, not null * @throws DateTimeException if unable to convert to a {@code LocalDate} */ public static LocalDate from(DateTimeAccessor dateTime) { if (dateTime instanceof LocalDate) { return (LocalDate) dateTime; } else if (dateTime instanceof LocalDateTime) { return ((LocalDateTime) dateTime).getDate(); } else if (dateTime instanceof ZonedDateTime) { return ((ZonedDateTime) dateTime).getDate(); } // handle builder as a special case if (dateTime instanceof DateTimeBuilder) { DateTimeBuilder builder = (DateTimeBuilder) dateTime; LocalDate date = builder.extract(LocalDate.class); if (date != null) { return date; } } return ofEpochDay(dateTime.getLong(EPOCH_DAY)); }
/** * Obtains an instance of {@code ZonedDateTime} from a date-time object. * <p> * A {@code DateTimeAccessor} represents some form of date and time information. This factory converts the * arbitrary date-time object to an instance of {@code ZonedDateTime}. * <p> * The conversion will try to obtain an instant first, then try to obtain the local date-time. * * @param dateTime the date-time object to convert, not null * @return the zoned date-time, not null * @throws DateTimeException if unable to convert to an {@code ZonedDateTime} */ public static ZonedDateTime from(DateTimeAccessor dateTime) { if (dateTime instanceof ZonedDateTime) { return (ZonedDateTime) dateTime; } try { ZoneId zone = ZoneId.from(dateTime); try { long epochSecond = dateTime.getLong(INSTANT_SECONDS); int nanoOfSecond = dateTime.get(NANO_OF_SECOND); return create(epochSecond, nanoOfSecond, zone); } catch (DateTimeException ex1) { LocalDateTime ldt = LocalDateTime.from(dateTime); return of(ldt, zone); } } catch (DateTimeException ex) { throw new DateTimeException("Unable to convert DateTimeAccessor to ZonedDateTime: " + dateTime.getClass(), ex); } }
/** * Creates a zoned date-time in this chronology from another date-time object. * <p> * This creates a date-time in this chronology based on the specified {@code DateTimeAccessor}. * <p> * This should obtain a {@code ZoneId} using {@link ZoneId#from(DateTimeAccessor)}. The date-time should be * obtained by obtaining an {@code Instant}. If that fails, the local date-time should be used. * * @param dateTime the date-time object to convert, not null * @return the zoned date-time in this chronology, not null * @throws DateTimeException if unable to create the date-time */ public ChronoZonedDateTime<C> zonedDateTime(DateTimeAccessor dateTime) { try { ZoneId zoneId = ZoneId.from(dateTime); ChronoDateTimeImpl<C> cldt; try { Instant instant = Instant.from(dateTime); cldt = localInstant(instant, zoneId); } catch (DateTimeException ex1) { cldt = ensureChronoLocalDateTime(localDateTime(dateTime)); } return ChronoZonedDateTimeImpl.ofBest(cldt, zoneId, null); } catch (DateTimeException ex) { throw new DateTimeException("Unable to convert DateTimeAccessor to ZonedDateTime: " + dateTime.getClass(), ex); } }
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); DateTimeAccessor cal = date; System.out.println("DoM: " + cal.get(DAY_OF_MONTH)); }
@Test(dataProvider = "sample_isoLocalDate", groups = { "tck" }) public void test_print_isoLocalDate(Integer year, Integer month, Integer day, String offsetId, String zoneId, String expected, Class<?> expectedEx) { DateTimeAccessor test = buildAccessor(year, month, day, null, null, null, null, offsetId, zoneId); if (expectedEx == null) { assertEquals(DateTimeFormatters.isoLocalDate().print(test), expected); } else { try { DateTimeFormatters.isoLocalDate().print(test); fail(); } catch (Exception ex) { assertTrue(expectedEx.isInstance(ex)); } } }
@Test(dataProvider = "sample_isoOffsetDate", groups = { "tck" }) public void test_print_isoOffsetDate(Integer year, Integer month, Integer day, String offsetId, String zoneId, String expected, Class<?> expectedEx) { DateTimeAccessor test = buildAccessor(year, month, day, null, null, null, null, offsetId, zoneId); if (expectedEx == null) { assertEquals(DateTimeFormatters.isoOffsetDate().print(test), expected); } else { try { DateTimeFormatters.isoOffsetDate().print(test); fail(); } catch (Exception ex) { assertTrue(expectedEx.isInstance(ex)); } } }
@Test(dataProvider = "sample_isoDate", groups = { "tck" }) public void test_print_isoDate(Integer year, Integer month, Integer day, String offsetId, String zoneId, String expected, Class<?> expectedEx) { DateTimeAccessor test = buildAccessor(year, month, day, null, null, null, null, offsetId, zoneId); if (expectedEx == null) { assertEquals(DateTimeFormatters.isoDate().print(test), expected); } else { try { DateTimeFormatters.isoDate().print(test); fail(); } catch (Exception ex) { assertTrue(expectedEx.isInstance(ex)); } } }
@Test(dataProvider = "sample_isoLocalTime", groups = { "tck" }) public void test_print_isoLocalTime(Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, String expected, Class<?> expectedEx) { DateTimeAccessor test = buildAccessor(null, null, null, hour, min, sec, nano, offsetId, zoneId); if (expectedEx == null) { assertEquals(DateTimeFormatters.isoLocalTime().print(test), expected); } else { try { DateTimeFormatters.isoLocalTime().print(test); fail(); } catch (Exception ex) { assertTrue(expectedEx.isInstance(ex)); } } }
@Test(dataProvider = "sample_isoTime", groups = { "tck" }) public void test_print_isoTime(Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, String expected, Class<?> expectedEx) { DateTimeAccessor test = buildAccessor(null, null, null, hour, min, sec, nano, offsetId, zoneId); if (expectedEx == null) { assertEquals(DateTimeFormatters.isoTime().print(test), expected); } else { try { DateTimeFormatters.isoTime().print(test); fail(); } catch (Exception ex) { assertTrue(expectedEx.isInstance(ex)); } } }
@Test(dataProvider = "sample_isoOffsetDateTime", groups = { "tck" }) 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) { DateTimeAccessor test = buildAccessor(year, month, day, hour, min, sec, nano, offsetId, zoneId); if (expectedEx == null) { assertEquals(DateTimeFormatters.isoOffsetDateTime().print(test), expected); } else { try { DateTimeFormatters.isoOffsetDateTime().print(test); fail(); } catch (Exception ex) { assertTrue(expectedEx.isInstance(ex)); } } }
@Test(dataProvider = "sample_isoZonedDateTime", groups = { "tck" }) 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) { DateTimeAccessor test = buildAccessor(year, month, day, hour, min, sec, nano, offsetId, zoneId); if (expectedEx == null) { assertEquals(DateTimeFormatters.isoZonedDateTime().print(test), expected); } else { try { DateTimeFormatters.isoZonedDateTime().print(test); fail(test.toString()); } catch (Exception ex) { assertTrue(expectedEx.isInstance(ex)); } } }
private DateTimeAccessor buildAccessor(LocalDate base, String offsetId, String zoneId) { MockAccessor mock = new MockAccessor(); mock.setFields(base); mock.setOffset(offsetId); mock.setZone(zoneId); return mock; }
private DateTimeAccessor buildAccessor(Integer year, Integer month, Integer day, Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId) { MockAccessor mock = new MockAccessor(); if (year != null) { mock.fields.put(YEAR, (long) year); } if (month != null) { mock.fields.put(MONTH_OF_YEAR, (long) month); } if (day != null) { mock.fields.put(DAY_OF_MONTH, (long) day); } if (hour != null) { mock.fields.put(HOUR_OF_DAY, (long) hour); } if (min != null) { mock.fields.put(MINUTE_OF_HOUR, (long) min); } if (sec != null) { mock.fields.put(SECOND_OF_MINUTE, (long) sec); } if (nano != null) { mock.fields.put(NANO_OF_SECOND, (long) nano); } mock.setOffset(offsetId); mock.setZone(zoneId); return mock; }
@Override public ChronoLocalDate<JapaneseChrono> date(DateTimeAccessor dateTime) { if (dateTime instanceof JapaneseDate) { return (JapaneseDate) dateTime; } return new JapaneseDate(LocalDate.from(dateTime)); }
@Override public ChronoLocalDate<HijrahChrono> date(DateTimeAccessor dateTime) { if (dateTime instanceof HijrahDate) { return (HijrahDate) dateTime; } return HijrahDate.ofEpochDay(dateTime.getLong(EPOCH_DAY)); }
@Override public ChronoLocalDate<ThaiBuddhistChrono> date(DateTimeAccessor dateTime) { if (dateTime instanceof ThaiBuddhistDate) { return (ThaiBuddhistDate) dateTime; } return new ThaiBuddhistDate(LocalDate.from(dateTime)); }
@Test(groups = { "tck" }) public void test_parseBest_secondOption() throws Exception { DateTimeFormatter test = DateTimeFormatters.pattern("yyyy-MM-dd[ZZZ]"); DateTimeAccessor result = test.parseBest("2011-06-30", OffsetDate.class, LocalDate.class); assertEquals(result, LocalDate.of(2011, 6, 30)); }
@Test(groups = { "implementation" }) public void test_interfaces() { Object obj = this.TEST_2007_07_15_12_30_40_987654321; assertTrue(obj instanceof DateTimeAccessor); assertTrue(obj instanceof Serializable); assertTrue(obj instanceof Comparable<?>); }
@Override protected List<DateTimeAccessor> samples() { DateTimeAccessor[] array = { this.TEST_2007_07_15_12_30_40_987654321, LocalDateTime.MAX_DATE_TIME, LocalDateTime.MIN_DATE_TIME, }; return Arrays.asList(array); }
@Test(groups = { "implementation" }) public void test_interfaces() { Object obj = this.TEST_2008_6_30_11_30_59_000000500; assertTrue(obj instanceof DateTimeAccessor); assertTrue(obj instanceof Serializable); assertTrue(obj instanceof Comparable<?>); }
@Test(groups = "tck") public void basicTest_isSupported_DateTimeField_null() { for (DateTimeAccessor sample : samples()) { assertEquals(sample.isSupported(null), false, "Failed on " + sample); } }
@Test(groups = "tck") public void basicTest_range_DateTimeField_unsupported() { for (DateTimeAccessor sample : samples()) { for (DateTimeField field : invalidFields()) { try { sample.range(field); fail("Failed on " + sample + " " + field); } catch (DateTimeException ex) { // expected } } } }
@Test(groups = "tck") public void basicTest_range_DateTimeField_null() { for (DateTimeAccessor sample : samples()) { try { sample.range(null); fail("Failed on " + sample); } catch (NullPointerException ex) { // expected } } }
@Test(groups = "tck") public void basicTest_get_DateTimeField_unsupported() { for (DateTimeAccessor sample : samples()) { for (DateTimeField field : invalidFields()) { try { sample.get(field); fail("Failed on " + sample + " " + field); } catch (DateTimeException ex) { // expected } } } }
@Test(groups = "tck") public void basicTest_get_DateTimeField_null() { for (DateTimeAccessor sample : samples()) { try { sample.get(null); fail("Failed on " + sample); } catch (NullPointerException ex) { // expected } } }
@Test(groups = "tck") public void basicTest_getLong_DateTimeField_unsupported() { for (DateTimeAccessor sample : samples()) { for (DateTimeField field : invalidFields()) { try { sample.getLong(field); fail("Failed on " + sample + " " + field); } catch (DateTimeException ex) { // expected } } } }
@Test(groups = "tck") public void basicTest_getLong_DateTimeField_null() { for (DateTimeAccessor sample : samples()) { try { sample.getLong(null); fail("Failed on " + sample); } catch (NullPointerException ex) { // expected } } }
@Test(groups = { "tck" }) public void basicTest_query() { for (DateTimeAccessor sample : samples()) { assertEquals(sample.query(new Query<String>() { @Override public String doQuery(DateTimeAccessor dateTime) { return "foo"; } }), "foo"); } }
private static void sort() { List<DateTimeAccessor> list = Arrays.<DateTimeAccessor> asList(LocalDate.now().plusMonths(3), LocalDate.now() .minusMonths(3), LocalDateTime.now()); Collections.sort(list, ChronoField.MONTH_OF_YEAR); System.out.println(list); }
/** * Returns a {@code Period} consisting of the number of years, months, days, hours, minutes, seconds, and * nanoseconds between two {@code DateTimeAccessor} instances. * <p> * The start date is included, but the end date is not. Only whole years count. For example, from * {@code 2010-01-15} to {@code 2011-03-18} is one year, two months and three days. * <p> * This method examines the {@link ChronoField fields} {@code YEAR}, {@code MONTH_OF_YEAR}, * {@code DAY_OF_MONTH} and {@code NANO_OF_DAY} The difference between each of the fields is calculated * independently from the others. At least one of the four fields must be present. * <p> * The four units are typically retained without normalization. However, years and months are normalized if * the range of months is fixed, as it is with ISO. * <p> * The result of this method can be a negative period if the end is before the start. The negative sign can * be different in each of the four major units. * * @param start the start date, inclusive, not null * @param end the end date, exclusive, not null * @return the period between the date-times, not null * @throws DateTimeException if the two date-times do have similar available fields * @throws ArithmeticException if numeric overflow occurs */ public static Period between(DateTimeAccessor start, DateTimeAccessor end) { if (Chrono.from(start).equals(Chrono.from(end)) == false) { throw new DateTimeException("Unable to calculate period as date-times have different chronologies"); } int years = 0; int months = 0; int days = 0; long nanos = 0; boolean valid = false; if (start.isSupported(YEAR)) { years = Jdk8Methods.safeToInt(Jdk8Methods.safeSubtract(end.getLong(YEAR), start.getLong(YEAR))); valid = true; } if (start.isSupported(MONTH_OF_YEAR)) { months = Jdk8Methods .safeToInt(Jdk8Methods.safeSubtract(end.getLong(MONTH_OF_YEAR), start.getLong(MONTH_OF_YEAR))); DateTimeValueRange startRange = Chrono.from(start).range(MONTH_OF_YEAR); DateTimeValueRange endRange = Chrono.from(end).range(MONTH_OF_YEAR); if (startRange.isFixed() && startRange.isIntValue() && startRange.equals(endRange)) { int monthCount = (int) (startRange.getMaximum() - startRange.getMinimum() + 1); long totMonths = ((long) months) + years * monthCount; months = (int) (totMonths % monthCount); years = Jdk8Methods.safeToInt(totMonths / monthCount); } valid = true; } if (start.isSupported(DAY_OF_MONTH)) { days = Jdk8Methods.safeToInt(Jdk8Methods.safeSubtract(end.getLong(DAY_OF_MONTH), start.getLong(DAY_OF_MONTH))); valid = true; } if (start.isSupported(NANO_OF_DAY)) { nanos = Jdk8Methods.safeSubtract(end.getLong(NANO_OF_DAY), start.getLong(NANO_OF_DAY)); valid = true; } if (valid == false) { throw new DateTimeException("Unable to calculate period as date-times do not have any valid fields"); } return create(years, months, days, nanos); }