Issue
Consider a String "2022-03-23 21:06:29.4933333 +00:00"
.
How do I parse the above DateTimeOffset String to LocalDateTime in Java?
I tried with the following DateTimeFormatter but the format seems to be incorrect:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss\[.nnnnnnn\] \[+|-\]hh:mm\]");
LocalDateTime dateTime = LocalDateTime.parse(timestamp, formatter)
Solution
First, start by having the JavDocs for DateTimeFormatter
at hand, this is going to really help determine which specifiers you need
The first thing to do is parse the text into a ZonedDateTime
, LocalDateTime
won’t parse a input value with a time zone (AFAIK), you "might" be able to force it, but what’s the point?
String text = "2022-03-23 21:06:29.4933333 +00:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSSSSS z");
ZonedDateTime zdt = ZonedDateTime.parse(text, formatter);
System.out.println(zdt);
This prints…
2022-03-23T21:06:29.493333300Z
Now you could use ZonedDateTime#toLocalDateTime
, but this won’t take into account the current time zone of the user/computer.
If you need to convert the ZonedDateTime
to LocalDateTime
, it’s best to do so in away which will translate the time (and date if required) to best represent the time within the current time zone (okay, I was confused typing it)
For example, converting the input value into my current time zone (+11 hours) would look like this…
ZoneId currentZone = ZoneId.systemDefault();
ZonedDateTime currentZDT = zdt.withZoneSameInstant(currentZone);
System.out.println(currentZDT);
LocalDateTime ldt = currentZDT.toLocalDateTime();
System.out.println(ldt);
which will print…
2022-03-24T08:06:29.493333300+11:00[Australia/Melbourne]
2022-03-24T08:06:29.493333300
This means that at 9:06pm on the 23rd March in Grinch (GMT), it was 8:06am on the 24th March where I live.
Now you can use different ZoneId
s to convert to a TimeZone
which is not the current computers TimeZone
, but I’ll leave that up to you to experiment with (for example, I used Convert ZonedDateTime to LocalDateTime at time zone to base my example on)
Answered By – MadProgrammer
Answer Checked By – Pedro (BugsFixing Volunteer)