从几毫秒计算周数,天数和小时数 [英] Calculate number of weeks , days and hours from milliseconds

查看:452
本文介绍了从几毫秒计算周数,天数和小时数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多类似的问题,但没有一个解决这个计算。使用javascript我可以很容易地找到例如:

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 被分配 518400000

要获得几周我会在下面

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

它完全符合 1 周。对于其他可能的输入,我想输出如下:

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

所以我做了 mil%(1000 * 7 * 24 * 3600)得到模数,从余数计算天数。但令人惊讶的是,这是我从控制台
1周,6天的答案,似乎以前计算的一周也是再次计入天数。

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.

推荐答案

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;

假设 mils 是非负的,这在<0,1000)范围内留下 mils ,留下分钟范围[0,60],在<0,24)范围内留下小时,并留下在[0,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).

这篇关于从几毫秒计算周数,天数和小时数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆