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

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

    Python

    It works by parsing the input string 1 character at a time, if the character is numerical it simply adds it (string add, not mathematical add) to the current value being parsed. If it is one of 'wdhms' the current value is assigned to the appropriate variable (week, day, hour, minute, second), and value is then reset ready to take the next value. Finally it sum the number of seconds from the 5 parsed values.

    def ytDurationToSeconds(duration): #eg P1W2DT6H21M32S
        week = 0
        day  = 0
        hour = 0
        min  = 0
        sec  = 0
    
        duration = duration.lower()
    
        value = ''
        for c in duration:
            if c.isdigit():
                value += c
                continue
    
            elif c == 'p':
                pass
            elif c == 't':
                pass
            elif c == 'w':
                week = int(value) * 604800
            elif c == 'd':
                day = int(value)  * 86400
            elif c == 'h':
                hour = int(value) * 3600
            elif c == 'm':
                min = int(value)  * 60
            elif c == 's':
                sec = int(value)
    
            value = ''
    
        return week + day + hour + min + sec
    

提交回复
热议问题