Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ISO 8601 duration with JavaScript

Tags:

How can I convert duration with JavaScript, for example:

PT16H30M

like image 877
cvelinho Avatar asked Feb 18 '13 10:02

cvelinho


People also ask

How do I specify the duration in an ISO 8601 format?

Briefly, the ISO 8601 notation consists of a P character, followed by years, months, weeks, and days, followed by a T character, followed by hours, minutes, and seconds with a decimal part, each with a single-letter suffix that indicates the unit. Any zero components may be omitted.

What is toISOString in Javascript?

toISOString() The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss. sssZ , respectively).

How do I convert ISO date to long date?

“javascript convert iso date to long date” Code Answer'sdate. getFullYear()+'-' + (date. getMonth()+1) + '-'+date. getDate();//prints expected format.

What is ISO date format in Javascript?

The standard is called ISO-8601 and the format is: YYYY-MM-DDTHH:mm:ss.sssZ.


1 Answers

You could theoretically get an ISO8601 Duration that looks like the following:

P1Y4M3W2DT10H31M3.452S

I wrote the following regular expression to parse this into groups:

(-)?P(?:([.,\d]+)Y)?(?:([.,\d]+)M)?(?:([.,\d]+)W)?(?:([.,\d]+)D)?T(?:([.,\d]+)H)?(?:([.,\d]+)M)?(?:([.,\d]+)S)? 

It's not pretty, and someone better versed in regular expressions might be able to write a better one.

The groups boil down into the following:

  1. Sign
  2. Years
  3. Months
  4. Weeks
  5. Days
  6. Hours
  7. Minutes
  8. Seconds

I wrote the following function to convert it into a nice object:

var iso8601DurationRegex = /(-)?P(?:([.,\d]+)Y)?(?:([.,\d]+)M)?(?:([.,\d]+)W)?(?:([.,\d]+)D)?T(?:([.,\d]+)H)?(?:([.,\d]+)M)?(?:([.,\d]+)S)?/;  window.parseISO8601Duration = function (iso8601Duration) {     var matches = iso8601Duration.match(iso8601DurationRegex);      return {         sign: matches[1] === undefined ? '+' : '-',         years: matches[2] === undefined ? 0 : matches[2],         months: matches[3] === undefined ? 0 : matches[3],         weeks: matches[4] === undefined ? 0 : matches[4],         days: matches[5] === undefined ? 0 : matches[5],         hours: matches[6] === undefined ? 0 : matches[6],         minutes: matches[7] === undefined ? 0 : matches[7],         seconds: matches[8] === undefined ? 0 : matches[8]     }; }; 

Used like this:

window.parseISO8601Duration('P1Y4M3W2DT10H31M3.452S'); 

Hope this helps someone out there.


Update

If you are using momentjs, they have ISO8601 duration parsing functionality available. You'll need a plugin to format it, and it doesn't seem to handle durations that have weeks specified in the period as of the writing of this note.

like image 107
crush Avatar answered Oct 24 '22 18:10

crush