使用JavaScript转换ISO 8601持续时间 [英] Convert ISO 8601 duration with JavaScript

查看:78
本文介绍了使用JavaScript转换ISO 8601持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用JavaScript转换持续时间,例如:

How can I convert duration with JavaScript, for example:

PT16H30M

推荐答案

从理论上讲,您可以获得一个ISO8601持续时间,如下所示:

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

P1Y4M3W2DT10H31M3.452S

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. 签名
  2. 年份
  3. 小时
  4. 分钟
  5. 第二

我编写了以下函数将其转换为漂亮的对象:

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]
    };
};

像这样使用:

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

希望这可以帮助某个人.

Hope this helps someone out there.

如果您使用的是 momentjs ,则它们具有ISO8601持续时间解析功能.您需要一个插件进行格式化,它似乎无法处理工期在撰写本说明之日的期间内已指定了几周.

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.

这篇关于使用JavaScript转换ISO 8601持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆