Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

iso8601 - Convert ISO 8601 duration with JavaScript

How can I convert duration with JavaScript, for example:

PT16H30M

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...