1

The output now is: The youtube video Title - PT1H2M11S

How can I convert this duration to a human readable format in seconds using Javascript?

I tried:

$(a).after("<br />" + b.items[0].snippet.title + " - " + b.items[0].contentDetails.duration..replace("PT","").replace("H",":").replace("M",":").replace("S","") +  "" );

But fails when duration is for example: PT4M9S then it outputs as 3:9 when it should be 3:09

function checkLink() {
    $("a.link").filter(function () {
        if ($(this).attr("href").match("(http|https)://(www.|m.)?youtube|youtu.be")) {
            youtube_id = $(this).attr("href").match(/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/)[2];
            $(this).html('<p style="text-align:center;"><img src="https://i.ytimg.com/vi/' + youtube_id + '/mqdefault.jpg" /></p>');
            var a = $(this).find("img");
            $.ajax({
                url: "https://www.googleapis.com/youtube/v3/videos?id=" + youtube_id + "&key=**********************&fields=items(snippet(title),contentDetails)&part=snippet,contentDetails",
                dataType: "json",
                success: function (b) {
                    $(a).after("<br />" + b.items[0].snippet.title + " - " + b.items[0].contentDetails.duration +  "" ); 
                }
            });
            return $(this).attr("href", "https://www.youtube.com/embed/" + youtube_id + "?autoplay=1")
        }
    }).colorbox({
        iframe: !0,
        innerWidth: 640,
        innerHeight: 425
    });
};
Dan Field
  • 20,885
  • 5
  • 55
  • 71
DannyS
  • 11
  • 3
  • 1
    It seems like this might be helpful to you: http://stackoverflow.com/questions/1267283/how-can-i-create-a-zerofilled-value-using-javascript - and then just break up your logic into discrete steps that use that zero-padding logic. – Dan Field Jun 08 '15 at 18:52
  • Thank you for your quick answer, although the linked question seemed helpful in the end i'd go for this one: http://stackoverflow.com/a/30649764/4987424 which solved what i wanted. – DannyS Jun 09 '15 at 22:19
  • Possible duplicate of [How to convert YouTube API duration (ISO 8601 duration in the format PT#M#S) to seconds](http://stackoverflow.com/questions/19061360/how-to-convert-youtube-api-duration-iso-8601-duration-in-the-format-ptms-to) – T J Jul 21 '16 at 06:33

0 Answers0