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?
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 or70
for the minute value), the adjacent value will be adjusted. E.g.new Date(2013, 13, 1)
is equivalent tonew Date(2014, 1, 1)
, both create a date for2014-02-01
(note that the month is 0-based).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With