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"
}
}
Your date string does not specify a time zone. You are also missing time information, while JavaScript dates store the time of day by design.
Your string is nearly valid JSON, so you can parse it via JSON.parse()
. It is only missing one closing }
bracket.
Considering the remarks above, you could 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"
When you send temporal types from Java to other systems you should be unambiguous about things like time of day and timezone. If the instance really is a Local Date you don't want to convert it to an instant on the universal timeline by selecting some arbitrary timezone. UTC is arbitrary. So is the default timezone.
14 March 2016 should mean the same thing to systems on opposite sides of the globe. ISO8601 exists for this purpose.
I recommend that when sending your 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 parse from JSON using LocalDate.parse(text, DateTimeFormatter.ISO_LOCAL_DATE)
.
JavaScript's Date
is more like the old Java Date
class and is similarly misnamed. However JavaScript's Date
will happily parse ISO8601 formatted strings either by construction or via the Date.parse()
function and will produce ISO8601 strings via Date.toISOString()
. Just note that JavaScript will interpret a missing timezone (signifying Local values in Java) as UTC. You can be unambiguous by always using the Zulu timezone when you mean UTC and assuming JS clients always send you zoned values.
Or just use JS-Joda.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With