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
.
Briefly, the ISO 8601 notation consists of a P character, followed by years, months, weeks, and days, followed by a T character, followed by hours, minutes, and seconds with a decimal part, each with a single-letter suffix that indicates the unit. Any zero components may be omitted.
ISO 8601 FormatsISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).
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;
}
Here is how you can get a youtube video data via Youtube API (v3) in a simple way and convert the video duration (ISO 8601) to seconds. Don't forget to change the { YOUR VIDEO ID } and { YOUR KEY } attribute in URL to your video id and your public google key. You can create a public key accessing the google developer console.
$.ajax({
url: "https://www.googleapis.com/youtube/v3/videos?id={ YOUR VIDEO ID }&part=contentDetails&key={ YOUR KEY }",
dataType: "jsonp",
success: function (data) { youtubeCallback (data); }
});
function youtubeCallback(data) {
var duration = data.items[0].contentDetails.duration;
alert ( convertISO8601ToSeconds (duration) );
}
function convertISO8601ToSeconds(input) {
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;
}
return (totalseconds);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With