Calculate the number of weeks, days and hours from milliseconds

There were many similar questions, but no one considered this calculation. Using javascript i, it is easy to find the number of milliseconds diff b / w 2 for ex:

var mil = Math.floor(new Date("1/1/2012") - new Date("1/7/2012")) 

mil assigned 518400000

to get weeks i would do below

 var weeks = mil / (1000*7*24*60*60); 

in the above example, it exactly corresponds to 1 week. For other possible inputs, I would like to get output as ex:

 n Weeks, y days , z hours 

So, I did mil % (1000*7*24*3600) to get the module, and from the remainder calculate the number of days. but it is surprising that this was the answer I received from the console 1 weeks , 6 days It seems that the previously calculated week is also taken into account for several days.

How to calculate them correctly?

+5
javascript date days hour
source share
2 answers
 var seconds = (mil / 1000) | 0; mil -= seconds * 1000; var minutes = (seconds / 60) | 0; seconds -= minutes * 60; var hours = (minutes / 60) | 0; minutes -= hours * 60; var days = (hours / 24) | 0; hours -= days * 24; var weeks = (days / 7) | 0; days -= weeks * 7; 

Assuming mils non-negative, this leaves mils in the range [0, 1000], leaves minutes and seconds in the range [0, 60), leaves hours in the range [0, 24] and leaves days in the range [0, 7).

+10
source share

Between them should be 6 days, not one week. The calculation of your weeks should round:

 var weeks = Math.floor(mil / (1000 * 7 * 24 * 60 * 60)); 

Also, your milliseconds are negative; do you want either

 var mil = new Date("1/7/2012") - new Date("1/1/2012"); 

or

 var weeks = Math.floor(Math.abs(mil) / (1000 * 7 * 24 * 60 * 60)); 
+3
source share

All Articles