Java 8 LocalDate to JavaScript Date

Moatez Bouhdid picture Moatez Bouhdid · Nov 15, 2016 · Viewed 16k times · Source

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"
        }
    }

Answer

Timo picture Timo · Nov 15, 2016

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"