Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 902
Mouaici_Med Avatar asked Jun 27 '26 05:06

Mouaici_Med


2 Answers

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>
like image 124
gyre Avatar answered Jun 28 '26 17:06

gyre


You need to include moment.js library.

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

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

in action: https://jsfiddle.net/w1e13Lne/

result:

enter image description here

like image 41
Unamata Sanatarai Avatar answered Jun 28 '26 19:06

Unamata Sanatarai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!