Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the dates 2014 Oct 31 and 2014 Nov 01 using date Object have same values in Javascript?

Why both dates in the below code have same valueOf() and getTime()?

<script>
var endDt = new Date(2014,10,31);
var endDt2 = new Date(2014,11,1);
alert("getTime()\nendDt : "+endDt.getTime()+"\nendDt2: "+endDt2.getTime());
alert("valueOf()\nendDt : "+endDt.valueOf()+"\nendDt2: "+endDt2.valueOf());
</script>

We can see that both values is equals.

I want to get the values to lock the user if user try a interval greater than 31 days. But when the user puts start Date(2014,10,01) and end Date(2014,11,1) the javascript interprets as end Date(2014,10,31). When i do calc. with difference between start date and end date both values is the same.

<script>
var startDt = new Date(2014,10,01);
var endDt 	= new Date(2014,10,31);
var endDt2 	= new Date(2014,11,1);
  
var diff  = endDt.getTime()-startDt.getTime();
var diff2 = endDt2.getTime()-startDt.getTime();

alert("getTime()\ndiff: "+diff+"\ndiff2: "+diff2);
  
diff  = endDt.valueOf()-startDt.valueOf();
diff2 = endDt2.valueOf()-startDt.valueOf();

alert("valueOf()\ndiff: "+diff+"\ndiff2: "+diff2);
</script>

Why are these values coming up the same, even though the provided dates are different?

like image 666
JmLavoier Avatar asked Feb 11 '23 17:02

JmLavoier


1 Answers

You are creating the wrong dates. Months are 0-based in JavaScript, so new Date(2014,10,31); is (theoretically) Nov 31st and new Date(2014,11,1) is Dec 1st.

Of course Nov 31st doesn't exist, so it's correct to Dec 1st.

From the big yellow box in the MDN documentation:

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).

like image 144
Felix Kling Avatar answered May 14 '23 08:05

Felix Kling