在Javascript/Angular中创建ISO 8601持续时间 [英] Create an ISO 8601 Duration in Javascript/Angular

查看:60
本文介绍了在Javascript/Angular中创建ISO 8601持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何在JavaScript中创建一个持续时间,然后将其格式化为ISO 8601持续时间,例如2分30秒将是"PT2M30S".

How would I create a duration in JavaScript then format this as an ISO 8601 duration, for example 2 mins 30 seconds would be "PT2M30S".

这可以用$ interval完成吗?还是可以通过Date().getTime()实现?

Could this be done with an $interval? Or can this be achieved with Date().getTime()?

我有一个互动,需要跟踪花费的时间,所以我会在开始或互动时获得日期,然后在结束时再次获取,彼此相减然后格式化为ISO 8601?努力寻找正确的语法或有用的库.

I have an interaction that I need to track time spent on, so would I get the date at the start or the interaction and then again at the end, subtract from each other then format as ISO 8601? Struggling to find correct syntax or a useful lib.

推荐答案

时刻是一个非常流行的日期处理库适用于能够在ISO8601中格式化持续时间的JavaScript.这是一个示例,该示例说明如何首先计算两个日期之间的差异,然后根据该差异生成持续时间字符串.

Moment is a very popular date manipulation library for JavaScript that's capable of formatting duration in ISO8601. Here's an example of how to first calculate a diff between two dates, and then generate a duration string from that diff.

var first = moment("2015-10-01"),
  second = moment("2015-10-02");

console.log(moment.duration(second.diff(first), "ms").toISOString());
// "PT24H"

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>

有关详细信息,请参见持续时间格式化文档.

Have a look at the documentation for duration formatting for more details.

这篇关于在Javascript/Angular中创建ISO 8601持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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