Robin
Robin

Reputation: 7306

Incorrect date shown in new Date() in 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

Upvotes: 33

Views: 49315

Answers (4)

Tushar
Tushar

Reputation: 1

Try this one:

const date = "2024-6-9";
const val = new Date(Date.UTC(...date.split("-").map((x, i) => i === 1? x - 1 : x)));
console.log(val);

Upvotes: 0

Ruud
Ruud

Reputation: 1372

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-05T00:00') to create the date object in local time.

Edit: while some browsers seem to support the yyyy-MM-dd HH:mm format, it's not officially supported, and, as mentioned in the comments, this doesn't work in Safari. I've updated the answer to use a T instead of a space between date and time.

Per the ECMAScript® 2023 Language Specification:

Date-only forms:

  • YYYY
  • YYYY-MM
  • YYYY-MM-DD

It also includes “date-time” forms that consist of one of the above date-only forms immediately followed by one of the following time forms with an optional UTC offset representation appended:

  • THH:mm
  • THH:mm:ss
  • THH:mm:ss.sss

Upvotes: 88

djnose
djnose

Reputation: 945

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)

Upvotes: 0

konenas
konenas

Reputation: 78

use setFullYear the syntax is Date.setFullYear(year,month,day)

mydate = new Date();
mydate.setFullYear(2016, 08, 05);

Upvotes: -1

Related Questions