问题
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