Difference in initialization of two dates in Javascript

2024/2/27 7:44:08

Why do these two dates are differents :

var date1 = new Date();
date1.setFullYear(2012); // year (four digits)
date1.setMonth(10); // month (from 0-11)
date1.setDate(1); // day of the month (from 1-31)var date2 = new Date(2012, 10, 1, 0, 0, 0, 0);

Result :

Date 1 : Sat Dec 01 2012 14:56:16 GMT+0100
Date 2 : Thu Nov 01 2012 00:00:00 GMT+0100

whereas these two dates are equals :

var date3 = new Date();
date3.setFullYear(2012); // year (four digits)
date3.setMonth(9); // month (from 0-11)
date3.setDate(1); // day of the month (from 1-31)var date4 = new Date(2012, 9, 1, 0, 0, 0, 0);

Result :

Date 3 : Mon Oct 01 2012 14:56:16 GMT+0200
Date 4 : Mon Oct 01 2012 00:00:00 GMT+0200

Another question is why do date1.setMonth(10) gives a date in December (should be November).


Finally got it. new Date() sets the date to the current date and time. In other words, October 31st (at the time of this writing).

When you then try to set the month to November, what's it to do? November only has 30 days... so it wraps it round to December.

If you change the order so that you set the day-of-month before the month, it works:

var date1 = new Date();
date1.setFullYear(2012); // year (four digits)
date1.setDate(1); // day of the month (from 1-31)
date1.setMonth(10); // month (from 0-11)

Or as implied by jbabey's answer:

var date1 = new Date();
date1.setFullYear(2012); // year (four digits)
date1.setMonth(10, 1); // month (from 0-11) and day (1-31)

The documentation isn't terribly clear, but it's at least suggestive:

If a parameter you specify is outside of the expected range, setMonth attempts to update the date information in the Date object accordingly. For example, if you use 15 for monthValue, the year will be incremented by 1 (year + 1), and 3 will be used for month.

("Accordingly" is far from precise, but it means the implementation is at least arguably correct...)


Related Q&A

How to disable dialog boxes - alert()?

I have a page where Im displaying iframes. The iframes are on the same domain with the website so I can edit and read the content of it, but I cant edit the source code of the iframes, because I dont h…

How can I avoid CORS restriction for web audio api?

I trying to create some visualization for audio-stream. But I run into CORS trouble when I try get access to raw audio data with createMediaElementSource() function.Is there a way to avoid this restric…

Pass JavaScript variable into AngualrJs ng-init

I have the following javascript variable defined and need to pass the memId value into AngularJs init function.<script type="text/javascript">var memId = "bb7de28f-0f89-4f14-8575-d…

Ajax call on Cordova ios SecurityError: DOM Exception 18

Hi Im building an iOS application via Cordova(5.1.1)/Phonegap and I have a problem I cant solve.A basic Ajax call throws a SecurityError: DOM Exception 18 I tried all the tricks regarding whitelisting …

parsing @ in MVC javascript section? [duplicate]

This question already has answers here:Escape @ character in razor view engine(16 answers)Closed 9 years ago.I am trying using Email RegEx in javascript section in MVC4. But RegEx has @ char. It is not…

Correctly declare static variables in JavaScript classes

In my code, I do the following (very simplified):class AddOrSelectAddress {static body; // <-- Errorstatic async open() {await $.get(basePath + Manage/AddOrSelectAddress, null, result => {this.bo…

Render JSON into HTML

I get JSON data with next code: $.getJSON("data.json",function foo(result) {$.each(result[1].data.children.slice(0, 10),function (i, post) {$("#content").append( <br> HTML …

Remove an item from local storage in reactjs

Is this the right code to remove an item from localStorage: onDelete(name) {console.log("ProductList.onDelete: ", name);let {products} = this.state;products = products.filter(product => pr…

React material-ui: centering items on Toolbar

I am trying to implement a toolbar on a page in which I have three ToolbarGroup components:<Toolbar><ToolbarGroup firstChild={true} float="left">{prevButton}</ToolbarGroup>&…

IonRangeSlider assign labels to values

I am using ionRangeSlider and I want assign labels to values or vice versa.So user can pick distance from beach with options: on beach, 100m, 200m, 300m, more than 300m but i need in post values like 0…