使用moment.js如何给出持续时间的特定格式 [英] Using moment.js how do I give a specific format for a duration

查看:283
本文介绍了使用moment.js如何给出持续时间的特定格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将来自API的持续时间(秒)指定为duration_seconds = 86485.

Given a duration of a number of seconds coming from an API as duration_seconds = 86485.

(1天0小时1分钟1秒)

(1 day, 0 hours, 1 minute, 1 second)

我打算使用moment.js将其转换为格式化的持续时间,如下所示:

I was going to use moment.js to convert this into formatted duration as follows:

 1. {d} {hh}:{mm}:{ss} (1d 00:01:01)
 2. {d}d {hh}h m{mm} s{ss} (1d 04h 30m 23s)

我还要确保以下几点:

  • 如果天数为0,则修剪天数(00:01:01-1分钟1秒)
  • hh:mm:ss从未修剪,1秒显示为00:00:01.
  • Days are trimmed if days is 0 (00:01:01 - for 1 minute 1 second)
  • hh:mm:ss are never trimmed, 1 second shows as 00:00:01.

我可以这样创建持续时间:

I can create the duration like this:

moment.duration(duration_seconds, 'seconds')

人性化功能不合适. 我也可以使用

The humanize function is not suitable as it approximates. I can also write my own with:

duration.get('d')
duration.get('h')
duration.get('m')
duration.get('s')

我似乎找不到内置函数,但我认为这将是显而易见的吗?是否有我缺少的东西,否则我可以将其PR到力矩库中.

I can't seem to find a built in function but I assume this would be an obvious one? Is there something I am missing, otherwise I can PR one into moment library.

这似乎暗示该功能仍然不存在: 使用moment.js ,如何将持续时间简化为最简化的形式?

This seems to imply that the function still does not exist: Using moment.js, How can I simplify a duration to its most simplified form?

推荐答案

moment-duration-格式插件可以为您提供帮助.

The moment-duration-format plugin can assist you with this.

// your input
var duration_seconds = 86485;

// create a moment-duration object
var duration = moment.duration(duration_seconds, 'seconds');

// format the object with a string
var formatted = duration.format('h[h] m[m] s[s]');

// displaying the output here
document.getElementById('output').innerHTML = formatted;

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
<div id="output" />

请注意,默认情况下,它将忽略不相关的单位,因此,如果您输入的是3,则只会说"3s",而不是"0h 0m 3s".

Note that by default it will omit units that are not relevant, so if your input is 3, it's just going to say "3s", not "0h 0m 3s".

如果要更改此行为,请根据文档设置trim:false /a>.例如,要获取您在注释中提到的格式,请使用:

If you want to change this behavior, set trim:false, per the documentation. For example, to get the format you mentioned in comments, use:

.format('hh:mm:ss', { trim: false })

这篇关于使用moment.js如何给出持续时间的特定格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆