Javascript显示毫秒为天:小时:分钟,无秒 [英] Javascript show milliseconds as days:hours:mins without seconds

查看:136
本文介绍了Javascript显示毫秒为天:小时:分钟,无秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在计算2个日期之间的差异,有很多不同的例子可供选择。返回的时间是毫秒,所以我需要将其转换成更有用的东西。



大多数示例为天:小时:分钟:秒或小时:分钟,但我需要天:小时:分钟,所以秒应该



我目前使用的方法接近,但显示3天为2.23.60,当它应该显示3.00.00,所以有些东西不是完全正确。当我从Web上的一个例子中获取当前代码时,我可以接受其他方法的建议。



我以毫秒为单位获得时间从结束日期减去开始日期如下: -

  date1 = new Date(startDateTime); 
date2 = new Date(endDateTime);
ms = Math.abs(date1 - date2)

我基本上需要采取ms

解决方案

这样的东西

 函数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));


I'm calculating the difference between 2 dates for which there are many differing examples available. The time returned is in milliseconds so I need to convert it into something more useful.

Most examples are for days:hours:minutes:seconds or hours:minutes, but I need days:hours:minutes so the seconds should be rounded up into the minutes.

The method I'm currently using gets close but shows 3 days as 2.23.60 when it should show 3.00.00 so something is not quite right. As I just grabbed the current code from an example on the web, I'm open to suggestions for other ways of doing this.

I'm obtaining the time in milliseconds by subtracting a start date from an end date as follows:-

date1 = new Date(startDateTime);
date2 = new Date(endDateTime);
ms = Math.abs(date1 - date2)

I basically need to take the ms variable and turn in into days.hours:minutes.

解决方案

Something like this?

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 ) );

这篇关于Javascript显示毫秒为天:小时:分钟,无秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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