Difference between ’01’ and ‘1’ in a JavaScript date [duplicate]

What is the difference between the dates ‘2015-10-01’ and ‘2015-10-1’ in JavaScript?

new Date('2015-10-1')

This returns 'Thu Oct 01 2015 00:00:00 GMT-0300'

new Date('2015-10-01')

Returns 'Wed Sep 30 2015 21:00:00 GMT-0300'

What I see after executing locally is

  • Date in local timezone
  • Date in UTC

As per the MDN docs, Date.parse will assume the date to be UTC format if it has complete DD else it will assume in local timezone format.


Detailed explanation regarding month change: (comments)

new Date('2015-10-1') when you execute this statement output is ‘Thu Oct 01 2015 00:00:00 GMT-0300’. i.e. its your local time and it is GMT -3hrs.

But when you execute the new Date('2015-10-01') the output is ‘Wed Sep 30 2015 21:00:00 GMT-0300’ which is in UTC time. i.e. 3hrs minus from your local time.

So it is 1st Oct midnight -3hrs, which is previous day’s 21hrs. i.e. Sep 30 21hrs.

From documentation:

new Date(dateString)

dateString

A string representing an RFC2822 or ISO 8601 date (other formats may be used, but results may be unexpected).

'2015-10-1' is neither of the supported formats and, as promised, you get unexpected results (whereas '2015-10-01' is a valid ISO 8601 date).

This is because JavaScript is expecting a certain amount of characters in the date string.

You have two formats here:

(YYYY-MM-DD)

and

(YYYY-MM-D)

I am surprised that the second is returning anything at all, as it doesn’t seem to fit any valid JavaScript Date String format. If it is returning as you say it is, then JavaScript is likely interpreting it as something other than Years, Months and Days.

Read More:   Javascript Function-Pointer Assignment


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts