0

I am trying to create a date object using a string in JavaScript but I am getting a date which is incorrect.

For example in the following piece of code I set the string to May 17, but the date I get in JavaScript is May 16. How do I fix this?

>dateString
"2016-05-17"
>var newDate = new Date(dateString)
>newDate
Mon May 16 2016 17:00:00 GMT-0700 (Pacific Daylight Time)
Alagappan Ramu
  • 2,270
  • 7
  • 27
  • 37
  • 1
    http://stackoverflow.com/a/5619588/3037869, for date operation use moment.js libary – seti Apr 07 '16 at 22:59
  • It's assuming your date string is in UTC. Note the time in the resulting date is exactly seven hours before midnight UTC, which corresponds to the offset (`GMT-0700`). – Heretic Monkey Apr 07 '16 at 23:03

1 Answers1

0

Don't use the Date constructor, or Date.parse, to parse date strings. The format:

"2016-05-17"

is treated as local by ISO 8601, but as UTC by ECMA-262. Some browsers will treat it as UTC, some as local and some won't parse it at all. It seems that your browser is treating it as UTC (per the standard) and you are in a time zone that is west of GMT, so you see a date that is one day earlier than expected.

Note that a date and time string without time zone (e.g. "2016-05-17T00:00:00") is treated as local by ECMA-262.

So always manually parse strings. A library can help, but often is more than is required. So if you want "2016-05-17" parsed as local, use:

function parseISOLocal(s) {
  var b = s.split(/\D/);
  return new Date(b[0], b[1]-1, b[2]);
}
                  
document.write(parseISOLocal('2016-05-17'));               
RobG
  • 142,382
  • 31
  • 172
  • 209