Reputation: 35
following Code to get difference in days:
var sDate = new Date('2014','08','30','0','0','0');
var eDate = new Date('2014','09','02','0','0','0');
var daysApart = Math.abs(Math.round((sDate-eDate)/86400000));
The result is 2. But if i use these dates:
var sDate = new Date('2014','08','25','0','0','0');
var eDate = new Date('2014','08','29','0','0','0');
var daysApart = Math.abs(Math.round((sDate-eDate)/86400000));
the result is 3.
On both dates it should be 3 but everytime i switch the month the function ignores the first of a month. I tested it with
var sDate = new Date('2014','08','31','0','0','0');
var eDate = new Date('2014','09','01','0','0','0');
but the result is 0. I've searched a lot at StackOverflow and Google Groups but couldn't find a solution. Any help would be great!
Upvotes: 1
Views: 54
Reputation: 1405
Someone someday decided that the month would be zero-based, you think you created a "30th of August" whereas in fact you created a "30th of September". In your second example you ask for the 31st of September, Which doesn't exist so you get the 30th os September instead.
Yes, this is quite retarded.
Upvotes: 0
Reputation: 207511
Time to learn about the Date object.
From MDN:
Constructor:
new Date(year, month, day, hour, minute, second, millisecond);
month
Integer value representing the month, beginning with 0 for January to 11 for December.
Run a simple test and see what is outputted:
console.log(new Date(2014,8,1,0,0,0));
console.log(new Date(2014,9,1,0,0,0));
So now what happens in your case?
var sDate = new Date('2014','08','31','0','0','0');
First they should be integers and not strings
You are saying month 8 which is September since we are zero based. Since September doe not have 31 days, the browser does not throw an error. It calculates what the day would be. As a result it changes it to the first of October.
Upvotes: 2