How can I convert duration with JavaScript, for example:
PT16H30M
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.
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).
“javascript convert iso date to long date” Code Answer'sdate. getFullYear()+'-' + (date. getMonth()+1) + '-'+date. getDate();//prints expected format.
The standard is called ISO-8601 and the format is: YYYY-MM-DDTHH:mm:ss.sssZ.
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With