最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Calculate number of weeks , days and hours from milliseconds - Stack Overflow

programmeradmin4浏览0评论

There were many similar questions around but none addressed this calculation. Using javascript i it is easy to find the number of milliseconds diff b/w 2 dates for ex:

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

mil is assigned 518400000

to get weeks i would do below

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

in the above example it exactly fits 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 modulus and from the remainder calculate number of days. but astonishingly this was answer i got from console 1 weeks , 6 days seems the week calculated before is also accounted for days again.

How should i calculate these correctly?

There were many similar questions around but none addressed this calculation. Using javascript i it is easy to find the number of milliseconds diff b/w 2 dates for ex:

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

mil is assigned 518400000

to get weeks i would do below

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

in the above example it exactly fits 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 modulus and from the remainder calculate number of days. but astonishingly this was answer i got from console 1 weeks , 6 days seems the week calculated before is also accounted for days again.

How should i calculate these correctly?

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Feb 23, 2012 at 4:57 DeeptechtonsDeeptechtons 11.1k27 gold badges105 silver badges178 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 12
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 is 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).

There should be 6 days between them, not one week. Your weeks calculation needs to round down:

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

Also, your milliseconds are negative; 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));
发布评论

评论列表(0)

  1. 暂无评论