javascriptyoutube-javascript-api

How to convert YouTube API duration (ISO 8601 duration in the format PT#M#S) to seconds


How can I manipulate a date time in the format PT#M#S with JavaScript?

for example: PT5M33S

I'd like to output as hh:mm:ss.


Solution

  • Here's the basic code to get total number of seconds and other parts. I feel uneasy doing this, as the rule says that any time you want to date logic you shouldn't :) But anyways, here it goes - Google made it not easy, providing total seconds in the getduration player API, and providing totally different format in the gdata api.

    var reptms = /^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/;
    var hours = 0, minutes = 0, seconds = 0, totalseconds;
    
    if (reptms.test(input)) {
      var matches = reptms.exec(input);
      if (matches[1]) hours = Number(matches[1]);
      if (matches[2]) minutes = Number(matches[2]);
      if (matches[3]) seconds = Number(matches[3]);
      totalseconds = hours * 3600  + minutes * 60 + seconds;
    }