Skip to content

Instantly share code, notes, and snippets.

@Fauntleroy
Created March 15, 2013 05:48
Show Gist options
  • Save Fauntleroy/5167736 to your computer and use it in GitHub Desktop.
Save Fauntleroy/5167736 to your computer and use it in GitHub Desktop.
Convert the YouTube v3 API's insane duration to something reasonable
var convertYouTubeDuration = function( yt_duration ){
var time_extractor = /([0-9]*)M([0-9]*)S$/;
var extracted = time_extractor.exec( yt_duration );
var minutes = parseInt( extracted[1], 10 );
var seconds = parseInt( extracted[2], 10 );
var duration = ( minutes * 60 ) + seconds;
return duration;
};
@hbtalha
Copy link

hbtalha commented Jul 14, 2021

According to documentation, it's possible to have days value.

If the video is at least one day long, the letters P and T are separated, and the value's format is P#DT#H#M#S.

For example, this video (Minecraft, ffs) has following value P1DT6H11M55S

Here's updated function to handle this

export function convertISO8601ToMs(duration: string): number  {
    const time_extractor = /^P([0-9]*D)?T([0-9]*H)?([0-9]*M)?([0-9]*S)?$/i;
    const extracted = time_extractor.exec(duration);
    if (extracted) {
        const days = parseInt(extracted[1], 10) || 0;
        const hours = parseInt(extracted[2], 10) || 0;
        const minutes = parseInt(extracted[3], 10) || 0;
        const seconds = parseInt(extracted[4], 10) || 0;
        return (days * 24 * 3600 * 1000) + (hours * 3600 * 1000) + (minutes * 60 * 1000) + (seconds * 1000);
    }
    return 0;
}

Really nice, thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment