Calculating Javascript Days Between Two Days

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 am running the above code, the answer should be 1 day. But it gives me 2 days. Can you help me?

+4
source share
2 answers

This is because months 0 indexed in JavaScript. So, your first date is in July, the second in August.

You are comparing with a month having 31 days, therefore, the correct difference is 2 days.

When I entered dates this way in JavaScript, I explicitly add an offset so that other encoders do not read it incorrectly, it is 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 the code "fixed" ...

+4
source

In javascript, the month starts from January 00 from June 05

 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, for example, 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); 
0
source

Source: https://habr.com/ru/post/1486871/


All Articles