如何将YouTube API持续时间(ISO 8601持续时间格式为PT#M#S)转换为秒

问题描述:

如何使用JavaScript以PT#M#S格式操作日期时间?

How can I manipulate a date time in the format PT#M#S with JavaScript?

例如: PT5M33S

我想输出 hh:mm:ss

这是获取总秒数和其他部分的基本代码。
这样做我感到不安,因为规则说任何时候你想要约会逻辑你不应该:)但是无论如何,谷歌让它变得不容易,在getduration播放器API提供总秒数,并在gdata api中提供完全不同的格式。

Here's the basic code to get total number of seconds and other parts. I feel uneasy doing this, as the rule says that any time you want to date logic you shouldn't :) But anyways, here it goes - Google made it not easy, providing total seconds in the getduration player API, and providing totally different format in the gdata api.

          var reptms = /^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/;
          var hours = 0, minutes = 0, seconds = 0, totalseconds;

          if (reptms.test(input)) {
            var matches = reptms.exec(input);
            if (matches[1]) hours = Number(matches[1]);
            if (matches[2]) minutes = Number(matches[2]);
            if (matches[3]) seconds = Number(matches[3]);
            totalseconds = hours * 3600  + minutes * 60 + seconds;
          }