Mit*_*tch 18 javascript datetime
我正在计算两个日期之间的差异,其中有许多不同的例子可用.返回的时间以毫秒为单位,因此我需要将其转换为更有用的内容.
大多数例子都是几天:小时:分钟:秒或小时:分钟,但我需要几天:小时:分钟,所以秒应该四舍五入到分钟.
我目前正在使用的方法接近但显示3天为2.23.60,当它应该显示3.00.00,所以有些东西不太正确.由于我刚从Web上的示例中获取当前代码,因此我愿意接受有关其他方法的建议.
我通过从结束日期减去开始日期来获得以毫秒为单位的时间,如下所示: -
date1 = new Date(startDateTime);
date2 = new Date(endDateTime);
ms = Math.abs(date1 - date2)
Run Code Online (Sandbox Code Playgroud)
我基本上需要使用ms变量并将其转入days.hours:minutes.
Mic*_*Mic 25
像这样的东西?
function dhm(t){
var cd = 24 * 60 * 60 * 1000,
ch = 60 * 60 * 1000,
d = Math.floor(t / cd),
h = Math.floor( (t - d * cd) / ch),
m = Math.round( (t - d * cd - h * ch) / 60000),
pad = function(n){ return n < 10 ? '0' + n : n; };
if( m === 60 ){
h++;
m = 0;
}
if( h === 24 ){
d++;
h = 0;
}
return [d, pad(h), pad(m)].join(':');
}
console.log( dhm( 3 * 24 * 60 * 60 * 1000 ) );
Run Code Online (Sandbox Code Playgroud)
Bri*_*lly 15
听起来像是Moment.js的工作.
var diff = new moment.duration(ms);
diff.asDays(); // # of days in the duration
diff.asHours(); // # of hours in the duration
diff.asMinutes(); // # of minutes in the duration
Run Code Online (Sandbox Code Playgroud)
在MomentJS中有很多其他格式化持续时间的方法.该文档是非常全面的.
Lau*_*rgé 10
不知道为什么,但其他人没有为我工作所以这里是我的
function dhm(ms){
days = Math.floor(ms / (24*60*60*1000));
daysms=ms % (24*60*60*1000);
hours = Math.floor((daysms)/(60*60*1000));
hoursms=ms % (60*60*1000);
minutes = Math.floor((hoursms)/(60*1000));
minutesms=ms % (60*1000);
sec = Math.floor((minutesms)/(1000));
return days+":"+hours+":"+minutes+":"+sec;
}
alert(dhm(500000));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
50912 次 |
| 最近记录: |