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

Javascript show milliseconds as days:hours:mins without seconds

本文关键字:分钟 小时 显示 Javascript      更新时间:2023-09-26

我正在计算两个日期之间的差异,有许多不同的例子可用。返回的时间以毫秒为单位,所以我需要把它转换成更有用的东西。

大多数例子都是days:hours:minutes:seconds或hours:minutes,但我需要days:hours:minutes,所以秒应该四舍五入成分钟。

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

我通过从结束日期减去开始日期来获得以毫秒为单位的时间,如下所示:-

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

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

像这样?

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

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

function dhm (ms) {
  const days = Math.floor(ms / (24*60*60*1000));
  const daysms = ms % (24*60*60*1000);
  const hours = Math.floor(daysms / (60*60*1000));
  const hoursms = ms % (60*60*1000);
  const minutes = Math.floor(hoursms / (60*1000));
  const minutesms = ms % (60*1000);
  const sec = Math.floor(minutesms / 1000);
  return days + ":" + hours + ":" + minutes + ":" + sec;
}

听起来像是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
在MomentJS中还有很多其他的方法来格式化持续时间。

给你:

http://jsfiddle.net/uNnfH/1

或者如果你不想使用一个正在运行的例子,那么:

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

不知道你需要多少答案,但这里有另一个-只是对一些已经给出的答案的另一个选择:

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

要小心这样的计算,跨越夏令时边界的时间段会引起问题。在UTC中工作并转换为本地时间总是更好的。

"返回的时间单位是毫秒,所以我需要把它转换成更有用的东西。"

你是从服务器取回时间还是这是纯粹的javascript?

有些代码真的有帮助。"有用的东西"有点模糊。

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

<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!

用moment.js试试这个:

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

当你想显示小时数时,你必须有一个变通方法:

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

此解决方案在本期中介绍。

改编自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;
};

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

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

然后继续计算

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

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

延长" moment.js"使用额外的功能formatDuration来正确格式化间隔,添加以下脚本:

this.moment.formatDuration = function (duration, timeFormat) {
    const ms = duration.asMilliseconds(),
        days = Math.floor(Math.abs(ms) / 8.64e7),
        msOnLastDay = Math.abs(ms) - days * 8.64e7;
    return (ms < 0 ? '-' : '') + (days !== 0 ? days + ' ' : '')
        + moment.utc(msOnLastDay).format(timeFormat ? timeFormat : 'HH:mm:ss.SSS');
};

10秒后将显示为"00:00:10.000"两天差1小时25分钟显示为"2 01:25:00.000"。时间格式可自定义

参见JSFiddle - https://jsfiddle.net/aldis/9x3f8b7q

中的运行示例

这个库对于解析毫秒似乎相当有用。它给你一个对象的属性,如天,小时,分钟等。

https://www.npmjs.com/package/parse-ms

这个输出毫秒数

https://github.com/sindresorhus/pretty-ms

我做了一个版本,只在需要时显示天数以及小时的填充。

const padZeroTwo = (n) => ('' + n).padStart(2, '0');
const msToDaysHoursMinutes = (ms) => {
  const days = Math.floor(ms / (24 * 60 * 60 * 1000));
  const daysMs = ms % (24 * 60 * 60 * 1000);
  const hours = Math.floor(daysMs / (60 * 60 * 1000));
  const hoursMs = ms % (60 * 60 * 1000);
  const minutes = Math.round(hoursMs / (60 * 1000)); // Rounds up to minutes
  let output = '';
  if (days > 0) {
    output += days + ':';
  }
  output += (days > 0 ? padZeroTwo(hours) : hours) + ':';
  output += padZeroTwo(minutes);
  return output;
};
// Tests
const hundredDaysTwentyHoursFiftyMinutesThirtySeconds = 8715030000;
const oneDayTwoHoursEightMinutesTwelveSeconds = 94092000;
const twoHoursFiftyMinutes = 10200000;
const twelveSeconds = 12000;
const fiftySeconds = 50000;
console.log(msToDaysHoursMinutes(hundredDaysTwentyHoursFiftyMinutesThirtySeconds)); // 100:20:51
console.log(msToDaysHoursMinutes(oneDayTwoHoursEightMinutesTwelveSeconds)); // 1:02:08
console.log(msToDaysHoursMinutes(twoHoursFiftyMinutes)); // 2:50
console.log(msToDaysHoursMinutes(twelveSeconds)); // 0:00
console.log(msToDaysHoursMinutes(fiftySeconds)); // 0:01

   const convertMsToDHM = (miliseconds) => {
  let days;
  let hours;
  let minutes;
  let seconds;
  let total_hours;
  let total_minutes;
  let total_seconds;
  total_seconds = parseInt(Math.floor(miliseconds / 1000));
  total_minutes = parseInt(Math.floor(total_seconds / 60));
  total_hours = parseInt(Math.floor(total_minutes / 60));
  days = parseInt(Math.floor(total_hours / 24));
  seconds = parseInt(total_seconds % 60);
  minutes = parseInt(total_minutes % 60);
  hours = parseInt(total_hours % 24);
  return `${padTo2Digits(days)}:${padTo2Digits(hours)}:${padTo2Digits(minutes)}`;
};
const padTo2Digits = num => num.toString().padStart(2, '0');