Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The date changing to one day before while converting JavaScript Date object to a JSON string

I want to pass a Date object (Date is "12/01/2019" in MM/DD/YYYY format) as JSON string to an API. But while converting this date (without considering time zone) into the JSON string, the date is changing to one day before. Please see the code given below:

var newDate = new Date("12/01/19");
console.log(newDate)        // Showing Sun Dec 01 2019 00:00:00 GMT+0530 (India Standard Time)
var jsonDate = JSON.stringify(newDate);
console.log(jsonDate)       // Showing "2019-11-30T18:30:00.000Z"

The Date Dec 01, 2019 changes to Nov 30, 2019. In my case, I can't consider the time or time zone. I can't use 'Moment JS' also.

Why does this happen? Can anyone specify the reason behind this weird problem?

like image 847
Vignesh VS Avatar asked May 12 '26 23:05

Vignesh VS


1 Answers

Because your date string is in a non-standard format, the Date constructor treats it as a local time (see the manual for Date.parse() in the section "Differences in assumed time zone"). However, JSON.stringify() calls Date.toJSON() which calls Date.toISOString() which always outputs the time with a zero UTC offset. As a result, you need to translate your date to UTC by subtracting the timezone offset, which can be obtained via Date.getTimezoneOffset().

Alternatively, provide an ISO format (YYYY-MM-DD) date string and no adjustment is required as the Date constructor will treat that as a UTC time.

// non-standard date format
var newDate = new Date('12/01/19');
console.log(newDate.toJSON());

var os = newDate.getTimezoneOffset();
newDate = new Date(newDate.getTime() - os * 60 * 1000);
console.log(newDate.toJSON());

// ISO format date
var newDate2 = new Date('2019-12-01');
console.log(newDate2.toJSON());
like image 128
Nick Avatar answered May 14 '26 13:05

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!