Converting Youtube Data API V3 video duration format to seconds in JavaScript/Node.js

后端 未结 15 1989
北海茫月
北海茫月 2020-12-05 07:09

I\'m trying to convert ISO 8601 string to seconds in JS/Node. The best I could come up with was:

function convert_time(duration) {
    var a = duration.match         


        
相关标签:
15条回答
  • 2020-12-05 07:31

    If you're using moment.js you can simply call...

    moment.duration('PT15M33S').asMilliseconds();
    

    = 933000 ms

    0 讨论(0)
  • 2020-12-05 07:31

    My solution:

    function convert_time(duration) {
      var total = 0;
      var hours = duration.match(/(\d+)H/);
      var minutes = duration.match(/(\d+)M/);
      var seconds = duration.match(/(\d+)S/);
      if (hours) total += parseInt(hours[1]) * 3600;
      if (minutes) total += parseInt(minutes[1]) * 60;
      if (seconds) total += parseInt(seconds[1]);
      return total;
    }
    

    Fiddle

    0 讨论(0)
  • 2020-12-05 07:32

    ES6:

    const durationToSec = formatted =>
      formatted
        .match(/PT(?:(\d*)H)?(?:(\d*)M)?(?:(\d*)S)?/)
        .slice(1)
        .map(v => (!v ? 0 : v))
        .reverse()
        .reduce((acc, v, k) => (acc += v * 60 ** k), 0);
    
    0 讨论(0)
  • 2020-12-05 07:36

    Assuming the input is valid, we can use the regex exec method to iterate on the string and extract the group sequentially:

    const YOUTUBE_TIME_RE = /(\d+)([HMS])/g;
    const YOUTUBE_TIME_UNITS = {
        'H': 3600,
        'M': 60,
        'S': 1
    }
    
    /**
     * Returns the # of seconds in a youtube time string
     */
    function parseYoutubeDate(date: string): number {
        let ret = 0;
        let match: RegExpExecArray;
        while (match = YOUTUBE_TIME_RE.exec(date)) {
            ret += (YOUTUBE_TIME_UNITS[match[2]]) * Number(match[1]);
        }
        return ret;
    }
    
    0 讨论(0)
  • 2020-12-05 07:36

    I think using moment.js will be an easier solution. But if someone is looking for a custom solution, here is a simple regex one for you:

    var regex = /PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/;
    var regex_result = regex.exec("PT1H11S"); //Can be anything like PT2M23S / PT2M / PT28S / PT5H22M31S / PT3H/ PT1H6M /PT1H6S
    var hours = parseInt(regex_result[1] || 0);
    var minutes = parseInt(regex_result[2] || 0);
    var seconds = parseInt(regex_result[3] || 0);
    var total_seconds = hours * 60 * 60 + minutes * 60 + seconds;
    
    0 讨论(0)
  • 2020-12-05 07:42

    I realize eval is unpopular, but here's the easiest and fastest approach I can imagine. Enjoy.

    function formatDuration(x) {
       return eval(x.replace('PT','').replace('H','*3600+').replace('M','*60+').replace('S', '+').slice(0, -1));
    }
    
    0 讨论(0)
提交回复
热议问题