convertYouTubeTimeFormatToSeconds
Function to convert YouTube duration format to seconds.
HTML
<div class="output"></div>
CSS
.value, .sec {
display: inline-block;
width: 150px;
}
.sec {
color: green;
}
JavaScript
test('PT3M17S');
test('PT10M');
test('PT10H');
test('PT1M');
test('PT1H');
test('PT1M1S');
test('PT1H1S');
test('PT1H1M1S');
test('PT1M38S');
test('PT1M38.467S');
test('');
test('lovely noise');
test('5 Hammers');
test(null);
function test(value) {
var sec = convertYouTubeTimeFormatToSeconds(value);
$(".output").append("<div class='value'>" + value + "</div>");
$(".output").append("<div class='sec'>" + sec + "</div>");
$(".output").append("<br>");
}
function convertYouTubeTimeFormatToSeconds(timeFormat) {
if ( timeFormat === null || timeFormat.indexOf("PT") !== 0 ) {
return 0;
}
// match the digits into an array
// each set of digits into an item
var digitArray = timeFormat.match(/\d+/g);
var totalSeconds = 0;
// only 1 value in array
if (timeFormat.indexOf('H') > -1 && timeFormat.indexOf('S') == -1 && timeFormat.indexOf('M') == -1) {
totalSeconds += getIntValue(digitArray[0]) * 60 * 60;
}
else if (timeFormat.indexOf('H') == -1 && timeFormat.indexOf('S') > -1 && timeFormat.indexOf('M') == -1) {
totalSeconds += getIntValue(digitArray[0]) * 60;
}
else if (timeFormat.indexOf('H') == -1 && timeFormat.indexOf('S') == -1 && timeFormat.indexOf('M') > -1) {
totalSeconds += getIntValue(digitArray[0]);
}
// 2 values in array
else if (timeFormat.indexOf('H') > -1 && timeFormat.indexOf('S') > -1 && timeFormat.indexOf('M') == -1) {
totalSeconds += getIntValue(digitArray[0]) * 60 * 60;
totalSeconds += getIntValue(digitArray[1]) * 60;
}
else if (timeFormat.indexOf('H') > -1 && timeFormat.indexOf('S') == -1 && timeFormat.indexOf('M') > -1) {
totalSeconds += getIntValue(digitArray[0]) * 60 * 60;
totalSeconds += getIntValue(digitArray[1]);
}
else if (timeFormat.indexOf('H') == -1 && timeFormat.indexOf('S') > -1 && timeFormat.indexOf('M') > -1) {
totalSeconds += getIntValue(digitArray[0]) * 60;
totalSeconds +=...