Javascript Javascript显示毫秒为天:小时:分钟没有秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8528382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:22:36  来源:igfitidea点击:

Javascript show milliseconds as days:hours:mins without seconds

javascriptdatetime

提问by Mitch

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.

我正在计算有许多不同示例可用的 2 个日期之间的差异。返回的时间以毫秒为单位,因此我需要将其转换为更有用的内容。

Most examples are for days:hours:minutes:seconds or hours:minutes, but I need days:hours:minutesso 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.

我目前使用的方法接近但显示 3 天为 2.23.60 时它应该显示 3.00.00 所以有些事情不太正确。由于我刚刚从网络上的示例中获取了当前代码,因此我愿意接受其他方法的建议。

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.

我基本上需要将 ms 变量转换为 days.hours:minutes。

回答by Mic

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

回答by Brian Kelly

Sounds like a job for Moment.js.

听起来像是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

There are a ton of other ways to format durations in MomentJS. The docsare very comprehensive.

在 MomentJS 中,还有很多其他方法可以格式化持续时间。该文档是非常全面的。

回答by Laurent Duvergé

Dont know why but the others didn't worked for me so here is mine

不知道为什么,但其他人没有为我工作,所以这是我的

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

回答by aroth

Here you go:

干得好:

http://jsfiddle.net/uNnfH/1

http://jsfiddle.net/uNnfH/1

Or if you don't want to play with a running example, then:

或者,如果您不想玩正在运行的示例,则:

window.minutesPerDay = 60 * 24;

function pad(number) {
    var result = "" + number;
    if (result.length < 2) {
        result = "0" + result;
    }

    return result;
}

function millisToDaysHoursMinutes(millis) {
    var seconds = millis / 1000;
    var totalMinutes = seconds / 60;

    var days = totalMinutes / minutesPerDay;
    totalMinutes -= minutesPerDay * days;
    var hours = totalMinutes / 60;
    totalMinutes -= hours * 60; 

    return days + "." + pad(hours) + "." + pad(totalMinutes);
}

回答by RobG

Dunno how many answers you need, but here's another - just another take on a few answers that have already been given:

不知道您需要多少答案,但这是另一个答案 - 只是对已经给出的几个答案的另一种看法:

function msToDHM(v) {
  var days = v / 8.64e7 | 0;
  var hrs  = (v % 8.64e7)/ 3.6e6 | 0;
  var mins = Math.round((v % 3.6e6) / 6e4);

  return days + ':' + z(hrs) + ':' + z(mins);

  function z(n){return (n<10?'0':'')+n;}
}

Take care with such calculations though, periods crossing daylight saving boundaries will cause issues. Always better to work in UTC and convert to local times for presentation.

但是,请注意此类计算,跨越夏令时边界的时段会导致问题。最好在 UTC 中工作并转换为本地时间进行演示。

回答by Travis J

"The time returned is in milliseconds so I need to convert it into something more useful."

“返回的时间以毫秒为单位,所以我需要将其转换为更有用的东西。”

Are you getting the time back from a server or is this pure javascript?

您是从服务器获取时间还是这是纯 javascript?

Some code would reallyhelp. "Something useful" is kind of vague.

一些代码真的会有所帮助。“有用的东西”有点含糊。

Here is an example, I think this is what you are talking about.

这是一个例子,我想这就是你所说的。

<script type="text/javascript">

//Set the two dates
var millennium =new Date(2000, 0, 1) //Month is 0-11 in JavaScript
today=new Date()
//Get 1 day in milliseconds
var one_day=1000*60*60*24

//Calculate difference btw the two dates, and convert to days
document.write(Math.ceil((today.getTime()-millennium.getTime())/(one_day))+
" days has gone by since the millennium!")

</script>
4367 days has gone by since the millennium!

回答by Robin Wieruch

With moment.js try this:

使用 moment.js 试试这个:

function getFormattedMs(ms) {
  var duration = moment.duration(ms);
  return moment.utc(duration.asMilliseconds()).format("mm:ss");
}

When you want to show hours you have to have a workaround:

当您想显示小时数时,您必须有一个解决方法:

function formatDuration(ms) {
  var duration = moment.duration(ms);
  return Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss");
}

This workaround in moment was introduced in this Issue.

此解决办法的时刻,这是引入了问题

回答by Michael Tranchida

Adapted from gist.github.com/remino/1563878. Seems a bit clearer to me what's going on.

改编自gist.github.com/remino/1563878。对我来说似乎更清楚发生了什么。

function convertMS(ms) {
  var d, h, m, s;
  s = Math.floor(ms / 1000);
  m = Math.floor(s / 60);
  s = s % 60;
  h = Math.floor(m / 60);
  m = m % 60;
  d = Math.floor(h / 24);
  h = h % 24;

  var pad = function (n) { return n < 10 ? '0' + n : n; };

  var result = d + '.' + pad(h) + ':' + pad(m);
  return result;
};

回答by serdarsen

Here is my solution in React with moment.js

这是我在 React 中使用 moment.js 的解决方案

https://codesandbox.io/s/milliseconds-to-human-readable-text-with-momentjs-in-react-0pgmq

https://codesandbox.io/s/milliseconds-to-human-readable-text-with-momentjs-in-react-0pgmq

import React from "react";
import ReactDOM from "react-dom";
import moment from "moment";

import "../styles.css";

function App() {
  const oneSecondInMillis = 1000;
  const oneMinuteInMillis = 60000;
  const oneHourInMillis = 3.6e6;
  const oneDayInMillis = 8.64e7;
  const oneMonthMillis = 2.628e9;
  const oneYearInMillis = 3.154e10; //3.154e10;

  const createTime = millis => new moment.duration(millis);

  const millisToReadable = millis => {
    let result = "";

    if (typeof millis !== "number") return "0 ms";

    let time = createTime(millis);

    let years = Math.floor(time.asYears());
    millis = millis - years * oneYearInMillis;
    time = createTime(millis);

    let months = Math.floor(time.asMonths());
    millis = millis - months * oneMonthMillis;
    time = createTime(millis);

    let days = Math.floor(time.asDays());
    millis = millis - days * oneDayInMillis;
    time = createTime(millis);

    let hours = Math.floor(time.asHours());
    millis = millis - hours * oneHourInMillis;
    time = createTime(millis);

    let minutes = Math.floor(time.asMinutes());
    millis = millis - minutes * oneMinuteInMillis;
    time = createTime(millis);

    let seconds = Math.floor(time.asSeconds());
    millis = millis - seconds * oneSecondInMillis;
    time = new moment.duration(millis);

    let milliseconds = Math.floor(time.asMilliseconds());

    if (years > 0) {
      result += ` ${years} y`;
    }
    if (years > 0 || months > 0) {
      result += ` ${months} m`;
    }
    if (years > 0 || months > 0 || days > 0) {
      result += ` ${days} d`;
    }
    if (years > 0 || months > 0 || days > 0 || hours > 0) {
      result += ` ${hours} h`;
    }
    if (years > 0 || months > 0 || days > 0 || hours > 0 || minutes > 0) {
      result += ` ${minutes} m`;
    }
    if (
      years > 0 ||
      months > 0 ||
      days > 0 ||
      hours > 0 ||
      minutes > 0 ||
      seconds > 0
    ) {
      result += ` ${seconds} s`;
    }
    result += ` ${milliseconds} ms`;

    return result;
  };

  const millis =
    2 * oneYearInMillis +
    7 * oneMonthMillis +
    20 * oneDayInMillis +
    10 * oneHourInMillis +
    8 * oneMinuteInMillis +
    50 * oneSecondInMillis +
    95;

  const result = millisToReadable(millis);

  return (
    <div className="App">
      <h1>Milliseconds to Human Readable Text</h1>
      <h2>{millis}</h2>
      <h2>{result}</h2>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

回答by Amadan

Without code, it's hard to tell exactly which error you have, but I suspect you're doing exactly as you said: rounding up. If rounding down is not good enough for you, here's how to round to closest:

没有代码,很难确切地说出您遇到了哪个错误,但我怀疑您正在按照您所说的做:四舍五入。如果四舍五入对您来说不够好,以下是四舍五入到最接近的方法:

var time = date.getTime();
if (time % 60000 >= 30000) time += 60000;

and then continue with the calculation.

然后继续计算。