是否有任何方法我可以使用moment.js格式方法持续时间对象?我在文档中找不到它,也没有看到它是持续时间对象的属性。
我希望能够做到以下几点:
var diff = moment(end).unix() - moment(start).unix();
moment.duration(diff).format('hh:mm:ss')
此外,如果有其他库可以轻松地容纳这种功能,我会很有兴趣推荐。
谢谢!
是否有任何方法我可以使用moment.js格式方法持续时间对象?我在文档中找不到它,也没有看到它是持续时间对象的属性。
我希望能够做到以下几点:
var diff = moment(end).unix() - moment(start).unix();
moment.duration(diff).format('hh:mm:ss')
此外,如果有其他库可以轻松地容纳这种功能,我会很有兴趣推荐。
谢谢!
当前回答
为了以这种格式显示工作时间,我需要这样做。 一开始我是这么做的。
moment.utc(totalMilliseconds).format("HH:mm:ss")
然而,任何超过24小时的时间都将重置为0。 但是分和秒是准确的。 所以我只用这部分来表示分和秒。
var minutesSeconds = moment.utc(totalMilliseconds).format("mm:ss")
现在我只需要总时间。
var hours = moment.duration(totalMilliseconds).asHours().toFixed()
为了得到我们都想要的格式,我们只需要把它们粘在一起。
var formatted = hours + ":" + minutesSeconds
如果totalMilliseconds是894600000,这将返回249:30:00。
希望这有帮助。请在评论中留下任何问题。;)
其他回答
我使用:
var duration = moment.duration("09:30");
var str = moment(duration._data).format("HH:mm");
我在var str中得到"09:30"
使用moment-duration-format。
客户端框架(例如:React)
import moment from 'moment';
import momentDurationFormatSetup from 'moment-duration-format';
momentDurationFormatSetup(moment);
const breakLengthInMinutes = moment.duration(breakLengthInSeconds, 's').format('m');
服务器(node . js)
const moment = require("moment-timezone");
const momentDurationFormatSetup = require("moment-duration-format");
momentDurationFormatSetup(moment);
const breakLengthInMinutes = moment.duration(breakLengthInSeconds, 's').format('m');
在这些情况下,我使用经典的format函数:
var diff = moment(end).unix() - moment(start).unix();
//use unix function instead of difference
moment.unix(diff).format('hh:mm:ss')
这是一个hack,因为时间差异被视为一个标准的时刻日期,一个早期的epoch日期时间,但这对我们的目标并不重要,你不需要任何插件
使用这行代码:
moment.utc(moment.duration(4500, "seconds").asMilliseconds()).format("HH:mm:ss")
不再需要(如果曾经有过的话)将持续时间转换为utc来解决这个问题。这就像将base10的“1”转换为二进制,然后说由于输出“1”看起来像base10,我们将没有任何问题,假设这是一个base10值,用于任何后续操作。
使用moment-duration-format,注意{trim: false}可以防止修剪:
moment.duration(1000000, "seconds").format("hh:mm:ss", { trim: false })
> "277:46:40"
moment.duration(0, "seconds").format("hh:mm:ss", { trim: false })
> "00:00:00"
让我们将其与不推荐的滥用utc的方法进行比较:
moment.utc(moment.duration(1000000, "seconds").asMilliseconds()).format('HH:mm:ss')
> "13:46:40"