admin管理员组

文章数量:1401158

I'm trying to get a UTC time from a Javascript front end to a Java backend. I wanted to acplish 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 acplish this as it seems like a very mon case.

I'm trying to get a UTC time from a Javascript front end to a Java backend. I wanted to acplish 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 acplish this as it seems like a very mon case.

Share Improve this question edited Jun 10, 2020 at 17:29 Arvind Kumar Avinash 79.8k10 gold badges92 silver badges135 bronze badges asked Jun 10, 2020 at 16:45 JonJon 2771 gold badge2 silver badges14 bronze badges 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? – Andreas 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. – Anonymous Commented Jun 10, 2020 at 17:32
Add a ment  | 

1 Answer 1

Reset to default 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' ment.

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

LocalDateTime.ofInstant(Instant.parse(str), ZoneId.systemDefault())

本文标签: Converting Javascript Date object to Java LocalDateTimeStack Overflow