java parse date with optional timezone

Solutions on MaxInterview for java parse date with optional timezone by the best coders in the world

showing results for - "java parse date with optional timezone"
Till
05 Nov 2016
1public class DateFormatTest {
2
3    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
4            "yyyy-MM-dd[[ ]['T']HH:mm[:ss][XXX]]");
5
6    private TemporalAccessor parse(String v) {
7        return formatter.parseBest(v,
8                                   ZonedDateTime::from,
9                                   LocalDateTime::from,
10                                   LocalDate::from);
11    }
12
13    @Test public void testDateTime1() {
14        assertEquals(LocalDateTime.of(2014, 9, 23, 14, 20, 59),
15                     parse("2014-09-23T14:20:59"));
16    }
17
18    @Test public void testDateTime2() {
19        assertEquals(LocalDateTime.of(2014, 9, 23, 14, 20),
20                     parse("2014-09-23 14:20"));
21    }
22
23    @Test public void testDateOnly() {
24        assertEquals(LocalDate.of(2014, 9, 23), parse("2014-09-23"));
25    }
26
27    @Test public void testZonedDateTime() {
28        assertEquals(ZonedDateTime.of(2014, 9, 23, 14, 20, 59, 0,
29                                      ZoneOffset.ofHoursMinutes(10, 30)),
30                     parse("2014-09-23T14:20:59+10:30"));
31    }
32
33}