Search code examples
javascriptisoduration

Convert duration form seconds to ISO format in javascript


I want to convert duration time from seconds to ISO format, like this:

 5400 => 'PT1H30M'

I tried:

var isoDuration = moment.duration(5400,'seconds').toISOString();
alert(isoDuration); 

But that doesn't work; in Chrome I get this error:

Uncaught ReferenceError: moment is not defined

Any ideas?


Solution

  • The code you were trying to use requires a library called Moment.js, which eases the difficulty of handling native Date objects in JavaScript.

    You need to include the Moment.js library via a <script> tag in order to execute this code:

    var isoDuration = moment.duration(5400,'seconds').toISOString();
    console.log(isoDuration);
    <!-- Include this tag somewhere *before* the code using `moment` runs -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>