Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect date shown in new Date() in JavaScript

Tags:

javascript

enter image description here

This is what I get in chrome console. I pass "2016-09-05"(YYYY-MM-DD) as the date and it shows me Sept 4,2016 as the date.

Another constructor shows the right date

enter image description here

Passing it comma separated needs some tokenizing + parsing + making month zero indexed which I want to avoid

like image 692
Robin Avatar asked Aug 30 '16 09:08

Robin


People also ask

What is new Date () in JavaScript?

The new Date() Constructor In JavaScript, date objects are created with new Date() . new Date() returns a date object with the current date and time.

What does new Date () return?

Return value Calling the Date() function (without the new keyword) returns a string representation of the current date and time, exactly as new Date().toString() does.

What is the format of new Date ()?

By default, when you run new Date() in your terminal, it uses your browser's time zone and displays the date as a full text string, like Fri Jul 02 2021 12:44:45 GMT+0100 (British Summer Time).

Does new Date () Return current date?

In JavaScript, we can easily get the current date or time by using the new Date() object. By default, it uses our browser's time zone and displays the date as a full text string, such as "Fri Jun 17 2022 10:54:59 GMT+0100 (British Summer Time)" that contains the current date, time, and time zone.


2 Answers

If you omit the time in the new Date(string) constructor, UTC time is assumed. So the displayed value is actually correct. Use new Date('2016-09-05 00:00') to create the date object in local time.

like image 101
Ruud Avatar answered Oct 19 '22 18:10

Ruud


You could use the Solution from UTC Date Conversion. Which basicall does the following:

console.log(new Date("2014-12-23"));
console.log(convertDateToUTC(new Date("2014-12-23")));

function convertDateToUTC(date) { 
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()); 
}

The output would be like that in the console (for me at least :D)

Tue Dec 23 2014 01:00:00 GMT+0100 (Mitteleuropäische Zeit)
Tue Dec 23 2014 00:00:00 GMT+0100 (Mitteleuropäische Zeit)

like image 22
djnose Avatar answered Oct 19 '22 18:10

djnose