Convert SimpleDateFormat to DateTimeFormatter

落花浮王杯 提交于 2019-12-04 01:26:22
Remlap21

So there may be other answers to this but what I came up caters for the most extreme case I have. Firstly I reduced dd/MM to d/M. This denotes the minimum number of expected characters so will parse double digits completely fine. Note you could also use new DateTimeFormatterBuilder().parseLenient() but this seemed unnecessary.

Secondly I decided to use the optional clause in the format pattern itself. This allows you to specify which parts may not be provided which is exactly the case I was trying to solve.

Leaving us with:

DateTimeFormatter.ofPattern("d/M/yyyy[' ']['T'][H:mm[:ss[.S]]][X]");

This will now handle providing a date with or without time including a T separator, seconds, millis and zone offset.

With any luck this helps someone else!

private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyyy[' ']['T'][H:mm[:ss[.S]]][X]");

public LocalDate getRobustLocalDate(String value) {
    try {
        return LocalDate.parse(value, formatter);
    } catch (DateTimeParseException e) {
        return null;
    }
}

@Test
public void testDates() {
    getRobustLocalDate("03/07/2016");               // 2016-07-03
    getRobustLocalDate("3/7/2016");                 // 2016-07-03
    getRobustLocalDate("3/7/2016 00:00:00");        // 2016-07-03
    getRobustLocalDate("3/7/2016 00:00:00.0+0100"); // 2016-07-03
    getRobustLocalDate("3/7/2016T00:00:00.0+0100"); // 2016-07-03
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!