【问题标题】:Formatting Duration in Correct Format `HH:MM`以正确格式“HH:MM”格式化持续时间
【发布时间】:2022-01-04 18:25:50
【问题描述】:

我有一些逻辑旨在根据输入的开始和停止时间生成格式化的持续时间:

  getFormattedDuration = async (stopValue, startValue) => {
    const durValue = moment(stopValue, "H:mm").diff(moment(startValue, "H:mm"));
    const t = moment.duration(durValue);

    const duration = {
      hours: t.hours(),
      minutes: t.minutes()
    }

    const formattedDuration = `0${duration.hours}:${duration.minutes}`;
    return formattedDuration;

    // I'm prepending a `0` here because I know the duration will never be above a certain limit - i.e. it will never get to a double digit number for hours.

  } 

这在大多数情况下都有效。但有时我会得到类似这样的输出:

duration:  Object {
  "hours": 0,
  "minutes": 8,
}

formattedDuration:  00:8

我想要的是00:08。如何在必要时用零填充,以确保获得正确格式的持续时间值 - 应该采用这种格式 hh:mm。 moment.js 有我可以用来处理这个问题的函数吗?

【问题讨论】:

    标签: javascript momentjs


    【解决方案1】:

    您可以使用 moment.js 中的 format() 函数。

    const m = moment('00:8','HH:mm').format('HH:mm');
    
    console.log(m) // "00:08"
    

    m = moment('00:8','HH:mm').format('HH:mm');
    
    console.log(m)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    【讨论】:

      【解决方案2】:

      您可以使用.padStart() 来确保有前导零。

      【讨论】:

        猜你喜欢
        • 2018-08-28
        • 1970-01-01
        • 2014-10-31
        • 2019-08-01
        • 2019-07-13
        • 1970-01-01
        • 1970-01-01
        • 2020-11-11
        • 2023-03-10
        相关资源
        最近更新 更多