4
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2013, 06, 30);
var secondDate = new Date(2013, 07, 01);
var diffDays = Math.round(Math.abs((secondDate.getTime() - firstDate.getTime()) / (oneDay)));

I run the above code the answer should be 1day. But It is giving me 2days. Can you help me?

Thirumalai murugan
  • 5,698
  • 8
  • 32
  • 54

2 Answers2

4

That's because months are 0 indexed in JavaScript. So your first date is in July, and the second one in August.

You're comparing with a month having 31 days, hence the correct difference of 2 days.

When I enter dates this way in JavaScript, I explicitly add the offset so that other coders don't read it wrong, it's too easy to make this error :

var firstDate = new Date(2013, 06 - 1, 30); // -1 due to the months being 0-indexed in JavaScript
var secondDate = new Date(2013, 07 - 1, 01);

Yes I had had my code "fixed"...

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Yeah, tricky one: http://stackoverflow.com/questions/1453043/zero-based-month-numbering – jdero Jun 18 '13 at 16:29
0

In javascript month is starting from 00-Jan since 05-june

var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2013, 05, 30);
var secondDate = new Date(2013, 06, 01);
var diffDays = (secondDate- firstDate)/oneDay;
alert(diffDays);

To avoid confusion you can use like the following

var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date('JUNE 30,2013');
var secondDate = new Date('JULY 01,2013');
var diffDays = (secondDate- firstDate)/oneDay;
alert(diffDays);
Thirumalai murugan
  • 5,698
  • 8
  • 32
  • 54