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

How to convert YouTube API duration (ISO 8601 duration in the format PT#M#S) to seconds

本文关键字:持续时间 格式 PT#M#S 转换 ISO YouTube API 8601      更新时间:2023-09-26

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

例如:PT5M33S

我想输出为hh:mm:ss.

这是获取总秒数和其他部分的基本代码。我这样做感到不安,因为规则说,任何时候你想约会逻辑,你不应该:)但无论如何,它在这里 - 谷歌让它变得不容易,在getduration播放器API中提供总秒数,并在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;
          }

以下是通过Youtube API(v3)以简单方式获取YouTube视频数据并将视频持续时间(ISO 8601)转换为秒的方法。不要忘记将网址中的 { 您的视频 ID } 和 { 您的密钥 } 属性更改为您的视频 ID您的公共 Google 密钥。 您可以创建访问 Google 开发者控制台的公钥。

  $.ajax({
       url: "https://www.googleapis.com/youtube/v3/videos?id={ YOUR VIDEO ID }&part=contentDetails&key={ YOUR KEY }",
       dataType: "jsonp",
       success: function (data) { youtubeCallback (data); }
  });
    function youtubeCallback(data) {
        var duration = data.items[0].contentDetails.duration;
        alert ( convertISO8601ToSeconds (duration) );
    }        
    function convertISO8601ToSeconds(input) {
        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;
        }
        return (totalseconds);
    }

虽然这些答案在技术上是正确的; 如果你打算做很多时间和持续时间,你应该看看momentjs。另请查看时刻持续时间格式,它使格式化持续时间与常规时刻js 时间一样简单

这两个模块如何轻松的示例

moment.duration('PT5M33S').format('hh:mm:ss')

这将输出 05:33。还有很多其他用途。

尽管YouTube使用ISO8601格式是有原因的,因为它是标准格式,但请记住这一点。

在 2023 年时刻的"时刻".js处于传统模式。

您可以使用 Luxon.js(Moment.js 的后代)的持续时间类来解析ISO8601持续时间。

import { Duration } from 'luxon'
// OP's desired hh:mm:ss format
> Duration.fromISO('PT20S').toISOTime({suppressMilliseconds: true})
'00:00:20'

// other useful outputs
> Duration.fromISO('PT2M42S').toHuman()
'2 minutes, 42 seconds'
> Duration.fromISO('PT1H16M5S').toMillis()
4565000
> Duration.fromISO('P1DT2H1S').toObject()
{ days: 1, hours: 2, seconds: 1 }

我通过检查单位左侧的两个索引 (H,M,S) 并检查它是否是一个数字来解决这个问题,如果不是,单位是个位数,我在前面加上一个额外的"0"。否则,我返回两位数字。

   function formatTimeUnit(input, unit){
     var index = input.indexOf(unit);
     var output = "00"
    if(index < 0){
      return output; // unit isn't in the input
    }
    if(isNaN(input.charAt(index-2))){
      return '0' + input.charAt(index-1);
    }else{
      return input.charAt(index-2) + input.charAt(index-1);
    }
  }

我这样做了几个小时,几分钟和几秒钟。如果输入中没有任何时间,我也会放弃小时数,这当然是可选的。

    function ISO8601toDuration(input){
     var H = formatTimeUnit(input, 'H');
     var M = formatTimeUnit(input, 'M');
     var S = formatTimeUnit(input, 'S');
    if(H == "00"){
      H = "";
    }else{
      H += ":"
    }
    return H  + M + ':' + S ;
  }

那就这样称呼吧

  duration = ISO8601toDuration(item.duration);

我用它来格式化 youtube 数据 API 视频持续时间。希望这对某人有所帮助

最简单的方法是使用时刻持续时间格式。不过,下面是一个自定义函数,用于将 YouTube API 持续时间响应转换为 hh:mm:ss 格式。

const convertISO8601ToStringWithColons = string => {
        let hours, minutes, seconds;
        if (string.includes("H")) {
            hours = string.slice(2, string.indexOf("H"));
        } else {
            hours = false;
        }
        if (string.includes("S")) {
            // checks if number is one-digit and inserts 0 in front of it
            if (isNaN(parseInt(string.charAt(string.indexOf("S") - 2)))) {
                seconds = "0" + string.charAt(string.indexOf("S") - 1)
            } else {
                seconds = string.slice(-3, -1)
            }
        } else {
            seconds = "00"
        }
        
        // determines how minutes are displayed, based on existence of hours and minutes
        if (hours) {
            if (string.includes("M")) {
                if (string.indexOf("M") - string.indexOf("H") === 3) {
                    minutes = string.slice(string.indexOf("H") + 1, string.indexOf("M"))
                } else {
                    minutes = "0" + string.charAt(string.indexOf("M") - 1)
                }
            } else {
                minutes = "00"
            }
        } else {
            if (string.includes("M")) {
                minutes = string.slice(2, (string.indexOf("M")))
            } else {
                minutes = "0"
            }   
        }
        // distinction because livestreams (P0D) are not considered
        return string === "P0D" ? "Live" : `${hours ? hours + ":" : ""}${minutes}:${seconds}`
    }
    
const textExamples = ["PT11H57M30S", "PT7H2M", "PT10H37S", "PT8H", "PT4M58S", "PT39M", "PT7S", "P0D"]
textExamples.forEach(element => {
    console.log(convertISO8601ToStringWithColons(element))
});