dapidmini
dapidmini

Reputation: 1625

parameter for javascript Date object is different from documentation?

I read in the documentation it says that for Date object, the month parameter is zero-based. but somehow my code doesn't return the month as zero-based.. is it because my computer's settings? will it affect other users when browsing my website?

I'm trying to get a Date object for the previous month.

what I tried:

var mydate = new Date(2017, 11, 1); // result: Date 2017-11-30T17:00:00.000Z
var mydate = new Date(2017, 12, 1); // result: Date 2017-12-31T17:00:00.000Z
var mydate = new Date(2018, 0, 1); // result: Date 2017-12-31T17:00:00.000Z

Upvotes: 0

Views: 42

Answers (2)

Karan Shishoo
Karan Shishoo

Reputation: 2802

The issue you are facing is not because of how the date is being returned it is due to the fact that your local time is ahead of UTC (by 7 hours), this causes the returned date (which is in UTC) to show as the previous day at 5pm [17:00:00.000Z] (when you don't specify a time it saves the time as 00:00:00.000Z) a solution to your problem would be to convert all times to a single timezone. It should not have any effect on users visiting your website if you use the same timezone for all your values.

Upvotes: 1

Sanchit Patiyal
Sanchit Patiyal

Reputation: 4920

From the docs in the Note section of parameters -

Note: Where Date is called as a constructor with more than one argument, the specified arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments.

var mydate = new Date(Date.UTC(2017, 11, 1)); 
console.log(mydate);
var mydate = new Date(Date.UTC(2017, 12, 1)); 
console.log(mydate);
var mydate = new Date(Date.UTC(2018, 0, 1));
console.log(mydate);

P.S why output for second is as 2018-01-01 is coz

Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.

Upvotes: 2

Related Questions