java parse date using DateTimeFormatterpublic class DateFormatTest {
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"yyyy-MM-dd[[ ]['T']HH:mm[:ss][XXX]]");
private TemporalAccessor parse(String v) {
return formatter.parseBest(v,
ZonedDateTime::from,
LocalDateTime::from,
LocalDate::from);
}
@Test public void testDateTime1() {
assertEquals(LocalDateTime.of(2019, 9, 15, 14, 20, 59),
parse("2019-09-15T14:20:59"));
}
@Test public void testDateTime2() {
assertEquals(LocalDateTime.of(2019, 9, 15, 14, 20),
parse("2019-09-15 14:20"));
}
@Test public void testDateOnly() {
assertEquals(LocalDate.of(2019, 9, 15), parse("2019-09-15"));
}
@Test public void testZonedDateTime() {
assertEquals(ZonedDateTime.of(2019, 9, 15, 14, 20, 59, 0,
ZoneOffset.ofHoursMinutes(10, 30)),
parse("2019-09-15T14:20:59+10:30"));
}
}