【问题标题】:Javascript show milliseconds as days:hours:mins without secondsJavascript将毫秒显示为天:小时:分钟,没有秒
【发布时间】:2011-12-16 00:19:58
【问题描述】:

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

大多数示例是天:小时:分钟:秒或小时:分钟,但我需要 天:小时:分钟,因此应将秒四舍五入为分钟。

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

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

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

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

【问题讨论】:

  • 愿意分享一些代码吗?
  • 听起来“你现在使用的方法”几乎是对的!为什么不修呢?
  • 你可以为你正在做的事情发布一些代码吗?看起来你肯定做错了。另外,请查看stackoverflow.com/questions/1056728/…

标签: javascript datetime


【解决方案1】:

这样的?

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

【讨论】:

  • 非常感谢 Mic,在所有示例中,我发现您的代码在向其抛出不同值时最可靠。非常感谢。
  • @Mic 谢谢,这里怎么加秒?
【解决方案2】:

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

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

【讨论】:

  • 我花了2个小时才找到!非常感谢你!
【解决方案3】:

听起来像是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 中还有很多其他方法可以格式化持续时间。 docs很全面。

【讨论】:

  • 这将如何解决问题。不会得到所需格式的结果。它给出了总小时数、总分钟数或总天数。当期望的结果是总天数时:小时:分钟
  • MomentJS 对此没有解决方案。上面的评论解释了它。
  • 尊重:明确询问天:小时:分钟的问题,而不是总值。
【解决方案4】:

给你:

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

【讨论】:

  • 感谢您的建议,我最终采用了许多不同的方法,而且我采用的方法很接近。我以前没见过 jsfiddle,所以感谢您向我介绍它。
【解决方案5】:

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

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 工作并转换为当地时间进行演示总是更好。

【讨论】:

    【解决方案6】:

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

    您是从服务器获取时间还是纯 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!
    

    【讨论】:

    【解决方案7】:

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

    这个解决方法是在这个Issue中引入的。

    【讨论】:

      【解决方案8】:

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

      【讨论】:

        【解决方案9】:

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

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

        然后继续计算。

        【讨论】:

          【解决方案10】:

          这是我在 React with 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);
          

          【讨论】:

            【解决方案11】:

            要使用额外的函数 formatDuration 扩展“moment.js”以正确格式化间隔,请添加此脚本:

            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”。两天一小时二十五分钟的差异将显示为“2 01:25:00.000”。时间格式可自定义。

            查看 JSFiddle 中的运行示例 - https://jsfiddle.net/aldis/9x3f8b7q

            【讨论】:

              【解决方案12】:

              这个库似乎对解析毫秒相当有用。它为您提供了一个具有天、小时、分钟等属性的对象...

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

              而这个可以打印几毫秒:

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

              【讨论】:

                【解决方案13】:

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

                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

                【讨论】:

                  猜你喜欢
                  • 2012-09-27
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2018-11-16
                  • 1970-01-01
                  • 2012-06-08
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多