【问题标题】:MomentJS - Convvert Milliseconds to format(1 Hour and 7 minutes)MomentJS - 将毫秒转换为格式(1 小时 7 分钟)
【发布时间】:2020-05-27 10:43:27
【问题描述】:

我要做一个转变。我正在使用MomentJS,并且我正在尝试将milliseconds 转换为1 Hour and 7 Mins 的格式以用于示例

我可以使用以下代码使其像这样工作 1,1 小时,其中interval 是以毫秒为单位的时间:

moment
      .duration(interval)
      .asSeconds()
      .toFixed(0)

我怎样才能使这项工作。获取ms 并将它们转换为人类可读的格式。

对了,我试过humanize的方法,但是没有覆盖。仅供参考..

【问题讨论】:

标签: javascript time momentjs


【解决方案1】:

Moment 似乎不支持您开箱即用的要求,但您可以使用 the get function 获取持续时间的各种时间单位(年、月、日...)的值。

根据这些信息,我整理了几个函数来生成您正在寻找的输出:

let duration = moment.duration(122101000);

let units = [
  {unit: "years", singular: "Year", plural: "Years"},
  {unit: "months", singular: "Month", plural: "Months"},
  {unit: "days", singular: "Day", plural: "Days"},
  {unit: "hours", singular: "Hour", plural: "Hours"},
  {unit: "minutes", singular: "Minute", plural: "Minutes"},
  {unit: "seconds", singular: "Second", plural: "Seconds"}
];

console.log(output(deconstruct(duration, units)));

function output(entries)
{
  let result = "";
  for (let i = 0; i < entries.length; i++) {
    let entry = entries[i];
    if (i > 0) {
      result += ', ' + (i == entries.length - 1 ? "and " : "");
    }
    result += entry.unitValue + " " + (entry.unitValue == 1 ? entry.unit.singular : entry.unit.plural);
  }
  return result;
}

function deconstruct(duration, units)
{
  let values = [], unitValue;
  for (let unit of units) {
    if (unitValue = duration.get(unit.unit)) {
      values.push({"unitValue": unitValue, "unit": unit})
    }
  }
  return values;
}
&lt;script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 2014-05-21
    • 2018-11-16
    • 2020-09-04
    • 2012-09-27
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    相关资源
    最近更新 更多