Create an ISO 8601 Duration in Javascript/Angular

旧巷老猫 提交于 2020-06-27 04:49:38

问题


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".

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

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.


回答1:


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.



来源:https://stackoverflow.com/questions/33821650/create-an-iso-8601-duration-in-javascript-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!