Java 8 Local Date in JavaScript Date

I would like to convert this Java LocalDate to a JavaScript Date :

 { "date": { "year": 2016, "month": "NOVEMBER", "dayOfMonth": 15, "monthValue": 11, "dayOfWeek": "TUESDAY", "era": "CE", "dayOfYear": 320, "leapYear": true, "chronology": { "id": "ISO", "calendarType": "iso8601" } } 
+6
source share
2 answers

Your date string does not have a time zone. You also lack time information, and JavaScript dates store the time of day by design.

Your string is almost true JSON, so you can parse it with JSON.parse() . Only the closing bracket is missing } .

Given the above comments, you can use the following approach:

 var input = JSON.parse('{"date":{"year":2016,"month":"NOVEMBER","dayOfMonth":15,"monthValue":11,"dayOfWeek":"TUESDAY","era":"CE","dayOfYear":320,"leapYear":true,"chronology":{"id":"ISO","calendarType":"iso8601"}}}'); var day = input.date.dayOfMonth; var month = input.date.monthValue - 1; // Month is 0-indexed var year = input.date.year; var date = new Date(Date.UTC(year, month, day)); console.log(date); // "2016-11-15T00:00:00.000Z" 
+7
source

When you send temporary types from Java to other systems, you should be unambiguous in things like time of day and time zone. If the instance is indeed a local date, you do not want to convert it to instant time on a universal timeline by choosing an arbitrary time zone. UTC is arbitrary. This is the default time zone.

March 14, 2016 should mean the same for systems on opposite sides of the globe. ISO8601 exists for this purpose.

I recommend this when sending Java LocalDate to your JS client by encoding it in JSON as a string in ISO8601 format using DateTimeFormatter.ISO_LOCAL_DATE.format(localDate) and parsing from JSON using LocalDate.parse(text, DateTimeFormatter.ISO_LOCAL_DATE) .

JavaScript Date more like the old Java Date class and similarly named incorrectly. However, JavaScript Date will successfully parse strings in ISO8601 format, either by construction or using the Date.parse() function, and will generate Date.toISOString() Date.toISOString() using Date.toISOString() . Just note that JavaScript will interpret the missing time zone (denoting local values โ€‹โ€‹in Java) as UTC. You can be unambiguous by always using the Zulu time zone when you mean UTC, and assuming that JS clients always send you zoned values.

Or just use JS-Joda.

0
source

Source: https://habr.com/ru/post/1012345/


All Articles