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

后端 未结 15 2031
北海茫月
北海茫月 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:52

    Here's my solution:

    function parseDuration(duration) {
        var matches = duration.match(/[0-9]+[HMS]/g);
    
        var seconds = 0;
    
        matches.forEach(function (part) {
            var unit = part.charAt(part.length-1);
            var amount = parseInt(part.slice(0,-1));
    
            switch (unit) {
                case 'H':
                    seconds += amount*60*60;
                    break;
                case 'M':
                    seconds += amount*60;
                    break;
                case 'S':
                    seconds += amount;
                    break;
                default:
                    // noop
            }
        });
    
        return seconds;
    }
    

提交回复
热议问题