Created
May 1, 2015 21:57
-
-
Save jrtaylor-com/42883b0e28a45b8362e7 to your computer and use it in GitHub Desktop.
Parse Youtube v3 API Duration to seconds with Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function youtubeDurationToSeconds(duration) { | |
var hours = 0; | |
var minutes = 0; | |
var seconds = 0; | |
// Remove PT from string ref: https://developers.google.com/youtube/v3/docs/videos#contentDetails.duration | |
duration = duration.replace('PT',''); | |
// If the string contains hours parse it and remove it from our duration string | |
if (duration.indexOf('H') > -1) { | |
hours_split = duration.split('H'); | |
hours = parseInt(hours_split[0]); | |
duration = hours_split[1]; | |
} | |
// If the string contains minutes parse it and remove it from our duration string | |
if (duration.indexOf('M') > -1) { | |
minutes_split = duration.split('M'); | |
minutes = parseInt(minutes_split[0]); | |
duration = minutes_split[1]; | |
} | |
// If the string contains seconds parse it and remove it from our duration string | |
if (duration.indexOf('S') > -1) { | |
seconds_split = duration.split('S'); | |
seconds = parseInt(seconds_split[0]); | |
} | |
// Math the values to return seconds | |
return (hours * 60 * 60) + (minutes * 60) + seconds; | |
} |
OMG, thanks for this!..
You are most welcome :) Made this for a project years ago, always nice to see it come in handy for someone else.
10/05/2021 EDIT: Found a bug, so added some extra bits
Amazing thank you. I made some filthy modifications that could look better, but give you back the string as H:M:S.
Return block is this:
var str = "";
if (hours != 0) { str += hours + ":"; }
if (minutes == 0) { str += "00" + ":"; }
else if (minutes < 10) { str += "0" + minutes + ":"; }
else if (minutes > 10) { str += minutes + ":"; }
else if (minutes == 0) { str += "00:" }
if (seconds > 0 && seconds < 10) { str += "0" + seconds; }
else if (seconds < 10) { str += "0" + seconds; }
else if (seconds > 10) { str += seconds; }
else if (seconds == 0) { str += "00" }
return str;
Nice addition @daveshirman
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OMG, thanks for this!..