【问题标题】:Moment JS duration shows wrong time?Moment JS持续时间显示错误的时间?
【发布时间】:2018-06-28 08:16:14
【问题描述】:

我正在尝试使用时刻 js 以及持续时间和格式的组合将持续时间(以秒为单位)转换为人类友好的输出。 我以秒为单位获取持续时间,然后像这样格式化它:

const value = 337650
const duration = (durationSeconds) => {
  const duration = moment.duration(durationSeconds, 'seconds')
  return moment.utc(duration.asMilliseconds()).format('D [days] HH:mm:ss')
}

console.log(`Duration: ${duration(value)}`)

输出

“时长:4 天 21:47:30”

JSBin here

我的问题是它似乎错了。像https://www.tools4noobs.com/online_tools/seconds_to_hh_mm_ss/ 这样的在线服务显示时间减少了一天。 我不确定这些服务正在使用什么库/算法,以及它们是否显示了正确的经过时间或时刻 js。 任何想法都非常感谢!

【问题讨论】:

  • 我们知道一天有 86400 秒。 337650 / 86400 = 3.9079 天,所以绝对少于 Moment 为您打印的四天。
  • 由于控制台输出显示持续时间包含_data: [object Object] { days: 3, hours: 21, ...,很明显是moment.utc().format() 部分实际上搞砸了。

标签: javascript time momentjs


【解决方案1】:

您似乎将持续时间转换为纪元时间,然后对其进行格式化,这是错误的。

查看这个 Moment 问题,了解有关持续时间格式的详细信息。 https://github.com/moment/moment/issues/1048

【讨论】:

    【解决方案2】:

    可以使用humanize方法进行简单的格式化:

    let value = 337650
    let duration = moment.duration(value, 'seconds')
    duration = duration.humanize()
    console.log(duration)
    

    “4 天”

    您可能想深入了解更复杂的格式:https://github.com/jsmreese/moment-duration-format

    【讨论】:

      【解决方案3】:

      尝试一些简单的事情:

      var x = 337650%86400; 
      var days = (337650 - x)/86400; 
      var y = x%3600; 
      var hours= (x-y)/3600; 
      var sec = y%60; 
      var mins=(y-sec)/60; 
      alert(days + ' days ' + hours+':'+mins+':'+sec)
      

      【讨论】:

        【解决方案4】:

        您可以使用 moment-duration-format 插件来格式化持续时间,以前的方法(从持续时间创建新的绝对日期)不起作用。当您将 337650 秒添加到 Unix 纪元开始时,您会得到 1970 年 1 月 4 日 21:47:30,这就是您将这一天视为 4 的原因。

        作为进一步说明这将如何导致严重错误的示例,假设我们需要格式化一个持续时间,例如 2700000 秒。这将为我们提供“1 天 06:00:00”的输出。为什么?因为它相当于 1970 年 2 月 1 日 06:00。 (实际结果将是 31 天,06:00:00)。

        我不认为我们可以责怪 moment.js 的作者(他们做得非常出色),只是没有像应该使用的那样在 moment.js 上使用 format 函数。

        通过使用 moment-duration-format 中的 format 函数,我们将格式设置为持续时间而不是绝对时间,并且我们得到了正确的结果!

        momentDurationFormatSetup(moment);
        
        const value = 337650
        const duration = (durationSeconds) => {
            const duration = moment.duration(durationSeconds, 'seconds')
            return duration.format('D [days] HH:mm:ss');
        }
        
        console.log(`Duration: ${duration(value)}`)
        document.getElementById('output').innerHTML = `Duration: ${duration(value)}`;
        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.2.2/moment-duration-format.min.js"></script>
        <div id="output">
        </div>

        JSFiddle:https://jsfiddle.net/t07ez8o4/9/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-03-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-04-09
          • 2021-12-29
          • 2020-12-11
          相关资源
          最近更新 更多