[SOLVED] Parse a String to LocaDateTime in Java


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)


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);

This prints…


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);
LocalDateTime ldt = currentZDT.toLocalDateTime();

which will print…


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 ZoneIds 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)

Leave a Reply

Your email address will not be published. Required fields are marked *