Migrating to Java 8 DateTime [duplicate]

岁酱吖の 提交于 2021-02-10 19:59:53

问题


I'm in the process of changing our existing SimpleDateFormat based code to use the new Java 8 LocalDateTime and ZonedDateTime classes.

I couldn't find an easy way to convert this piece.

Considering sample date and format.

String testDate = "2012-12-31T10:10:10-06:00";
String testFormat = "yyyy-MM-dd'T'HH:mm:ss";

Existing code,

SimpleDateFormat sdf = new SimpleDateFormat(testFormat);
System.out.println(sdf.parse(testDate));

This piece works for both the date value containing timezone offset like mentioned above or not. It ignores the timezone if provided and in both cases defaults to the system timezone.

However if I replace it with below code,

DateTimeFormatter df = DateTimeFormatter.ofPattern(testFormat);
LocalDateTime ldt = LocalDateTime.parse(testDate, df);
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
System.out.println(zdt.toString());

It fails for the above format. To get it to work, I have to get rid of the timezone bit in the date i.e. convert it to "2012-12-31T10:10:10" or then change the format to include timezone details i.e. 'z'.

So from my initial tests at least it seems the new classes are pretty strict from matching the format to the T unlike SimpleDateFormat. I even tried marking the DateTimeFormater.setLineant(), but that too didn't help. Or maybe there are some other classes which can work in this case, just that I am not aware of them.

To add more details as why i want to have the legacy behavior using the new API's. In our product we expose these API's which end customer can use, so the API in question accepts both the datetime value in string and the format and used "SimpleDateFormat". So i want existing behavior to continue even with the new API's just so that we continue to maintain backward compatibility.

For now the only solution for above example i have come up with is handle it as an exception case,

DateTimeFormatter df = DateTimeFormatter.ofPattern(testFormat);
LocalDateTime ldt = null;
try {
   ldt = LocalDateTime.parse(testDate, df);
} catch (DateTimeParseException dtpException) {
   ldt = ZonedDateTime.parse(testDate).toLocalDateTime();
}
if (ldt != null) zdt = ldt.atZone(ZoneId.systemDefault());

Can someone share some pointers around this use case?

来源:https://stackoverflow.com/questions/54031601/migrating-to-java-8-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!