1

I'm trying to get a UTC time from a Javascript front end to a Java backend. I wanted to accomplish this by using Date.toISOString() and sending that object to the Java backend. However, an issue I noticed is that toISOString() returns the timestamp in YYYY-MM-DDTHH:mm:ss.sssZ format, and this format does not match any of the Java 8 pre-defined LocalDateTime formatters.

My question is, is there a best practice to do what I'm trying to do? I'm aware I can write a custom Java formatter to match the Javascript output. However, I wondered if there was a standard way to accomplish this as it seems like a very common case.

2
  • 2
    LocalDateTime in which time zone? If server time zone, use LocalDateTime.ofInstant(Instant.parse(dateString), ZoneId.systemDefault()) --- Are you sure you want a local date/time? Commented Jun 10, 2020 at 16:53
  • 2
    LocalDateTime is the wrong class to use on the Java side. Your ISO string defines a point in time. LocalDateTime cannot represent that. Use Instant or ZonedDateTime. Commented Jun 10, 2020 at 17:32

1 Answer 1

5

There are default ISO date formatters available. You can use following

LocalDateTime date = LocalDateTime.parse(str, DateTimeFormatter.ISO_DATE_TIME);

Note that this will assume the LocalDateTime of UTC timezone.

Update: as per Andreas' comment.

If you wish to get instance of LocalDateTime in server timezone, use

LocalDateTime.ofInstant(Instant.parse(str), ZoneId.systemDefault())
Sign up to request clarification or add additional context in comments.

2 Comments

That ignores the time zone, making the LocalDateTime be UTC in this case. How do you know OP wants the local date/time in UTC?
You are right, ISO_DATE_TIME does work! I was under the impression that it wouldn't because the examples provided on the Java docs were '2011-12-03T10:15:30', '2011-12-03T10:15:30+01:00' and '2011-12-03T10:15:30+01:00[Europe/Paris]'. I did not realize the Z was a valid zone it would detect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.