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

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

提交回复
热议问题