Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 LocalDate to 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"
        }
    }
like image 426
Moatez Bouhdid Avatar asked Nov 15 '16 14:11

Moatez Bouhdid


2 Answers

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"
like image 103
TimoStaudinger Avatar answered Nov 16 '22 22:11

TimoStaudinger


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.

like image 20
Dave Avatar answered Nov 16 '22 22:11

Dave