Hi I want to convert String value 2020-12-16T19:20:30 01:00 UTC to either LocalDateTime or ZonedDateTime in java
I tried solution:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("YYYY-MM-DDThh:mm:ssTZD", Locale.ENGLISH);
final String responseTimeStamp = "2020-12-16T19:20:30 01:00 UTC";
ZonedDateTime zdt = ZonedDateTime.parse(responseTimeStamp, dtf);
Which gives me the error
Exception in thread "main" java.lang.IllegalArgumentException: Unknown pattern letter: T at java.base/java.time.format.DateTimeFormatterBuilder.parsePattern(DateTimeFormatterBuilder.java:1815) at java.base/java.time.format.DateTimeFormatterBuilder.appendPattern(DateTimeFormatterBuilder.java:1712) at java.base/java.time.format.DateTimeFormatter.ofPattern(DateTimeFormatter.java:588) at learning/learning.SpringDemo.main(SpringDemo.java:21)
CodePudding user response:
There are a few things wrong with your code, i suggest you to take a look at the DateTimeFormatter documentation.
- YYYY -> This means week-based-year, you can have a look here to see the difference between year-of-era. So you should be using yyyy.
- DD -> This means day-of-year, so December 16 is equal to 350. In your case you want to use dd, day-of-month.
- T -> There isn't a pattern for T, so you can put it like a text to formmat you date 'T'
- TZD -> I don't know what you are trying to use here and i couldn't find the patter 03:00 UTC, you can try to use O
So your final pattern should be "yyyy-MM-dd'T'HH:mm:ssO". It doens't work for UTC and i couldn't find it on ZoneId list, maybe because UTC is 00:00 already, so UTC 01:00 is equal to 01:00
After a lot of working understanding the pattern, i found out that you are looking for ISO_ZONED_DATE_TIME, so you could just change your code like below:
DateTimeFormatter dtf = DateTimeFormatter.ISO_ZONED_DATE_TIME;
final String responseTimeStamp = "2020-12-16T19:20:30 01:00";
ZonedDateTime zdt = ZonedDateTime.parse(responseTimeStamp, dtf);
