Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert milliseconds to an ISO 8601 duration

What is the easiest way to convert a time duration in milliseconds to an ISO 8601 duration using Moment.js?

For example:

3600000 milliseconds > PT1H
like image 991
Channa Avatar asked Feb 02 '26 22:02

Channa


1 Answers

Since this is currently one of the top results when searching for how to convert milliseconds to an ISO 8601 duration with JavaScript, here is an approach using vanilla JS for those that can't or don't want to use Moment.js.

const duration = (ms) => {
  const dt = new Date(ms);
  const units = [
    ['Y', dt.getUTCFullYear() - 1970],
    ['M', dt.getUTCMonth()],
    ['D', dt.getUTCDate() - 1],
    ['T', null],
    ['H', dt.getUTCHours()],
    ['M', dt.getUTCMinutes()],
    ['S', dt.getUTCSeconds()]
  ];
  
  let str = units.reduce((acc, [k, v]) => {
    if (v) {
      acc += v + k;
    } else if (k === 'T') {
      acc += k;
    } 
    return acc;
  }, '');
  
  str = str.endsWith('T') ? str.slice(0, -1) : str;
  return str ? `P${str}` : null;
};

console.log(duration(110723405000));
// P3Y6M4DT12H30M5S
console.log(duration(3600000));
// PT1H
like image 162
benvc Avatar answered Feb 05 '26 11:02

benvc



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!