Get duration using YouTube API - php

I need to get the video duration using Youtube API V3. My application was working fine with API V3 but now it doesn't work.
I found a working example and it works:
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=[VIDOID]&key=[API KEY]");
$duration =json_decode($dur, true);
foreach ($duration['items'] as $vidTime) {
$vTime= $vidTime['contentDetails']['duration'];
}
Credits: Youtube API v3 , how to get video durations?
This will return the time format something like this.
PT24M30S
How can I convent this to a readable time. Like 24:30?

I can't believe it, anyone have used DateInterval, why? It's just like this:
$duration = new DateInterval('PT24M30S');
print $duration->format('%H:%i:%s'); // outputs: 00:24:30
Helpful links:
The DateInterval class
DateInterval::format

One possible way is to use the function str_replace();
$stamp = "PT24M30S";
$formated_stamp = str_replace(array("PT","M","S"), array("",":",""),$stamp);
echo $formated_stamp; //should give "24:30"
Bonus content - leading zeros
In order to add leading zeros one must first split the string up with explode(), then format the numbers idividually with sprintf(); and finally add it all together again.
$exploded_string = explode(":",$formated_stamp);
$new_formated_stamp = sprintf("%02d", $exploded_string[0]).":".sprintf("%02d", $exploded_string[1]);

$time_format = "PT24M30S ";
preg_match_all('/(\d+)/',$time_format,$parts);
$hours = floor($parts[0][0]/60);
$minutes = $parts[0][0]%60;
$seconds = $parts[0][1];
echo $hours . ": ". $minutes .":". $seconds;

video resource contains a duration field which is a string of the following format. It will be up to you the developer to reformat it as necessary for your application and needs.
contentDetails.duration
The length of the video. The tag value is an ISO 8601 duration. For
example, for a video that is at least one minute long and less than
one hour long, the duration is in the format PT#M#S, in which the
letters PT indicate that the value specifies a period of time, and the
letters M and S refer to length in minutes and seconds, respectively.
The # characters preceding the M and S letters are both integers that
specify the number of minutes (or seconds) of the video. For example,
a value of PT15M33S indicates that the video is 15 minutes and 33
seconds long.
If the video is at least one hour long, the duration is in the format
PT#H#M#S, in which the # preceding the letter H specifies the length
of the video in hours and all of the other details are the same as
described above. If the video is at least one day long, the letters P
and T are separated, and the value's format is P#DT#H#M#S. Please
refer to the ISO 8601 specification for complete details.
As to how to do it I would have to say remove the PT and the S and replace the M with a :. It will probably require some testing on your part depending on what happens when a value is null. I would do some research into ISO-8061

I use the following function to convert the YouTube duration. Simply replace $yt with the format YouTube provided you and it'll print it out nice and readable.
function ConvertYoutubeVideoDuration($yt){
$yt=str_replace(['P','T'],'',$yt);
foreach(['D','H','M','S'] as $a){
$pos=strpos($yt,$a);
if($pos!==false) ${$a}=substr($yt,0,$pos); else { ${$a}=0; continue; }
$yt=substr($yt,$pos+1);
}
if($D>0){
$M=str_pad($M,2,'0',STR_PAD_LEFT);
$S=str_pad($S,2,'0',STR_PAD_LEFT);
return ($H+(24*$D)).":$M:$S"; // add days to hours
} elseif($H>0){
$M=str_pad($M,2,'0',STR_PAD_LEFT);
$S=str_pad($S,2,'0',STR_PAD_LEFT);
return "$H:$M:$S";
} else {
$S=str_pad($S,2,'0',STR_PAD_LEFT);
return "$M:$S";
}
}

Solution PHP
function covtime($youtube_time){
preg_match_all('/(\d+)/',$youtube_time,$parts);
$hours = $parts[0][0];
$minutes = $parts[0][1];
$seconds = $parts[0][2];
if($seconds != 0)
return $hours.':'.$minutes.':'.$seconds;
else
return $hours.':'.$minutes;
}

Related

Highchart add three zeros in the loop

I have use library chart from this page link. Unfortunately, the data I download is not compatible, for example:
I get from JSON time:
time: 1346803200
this time is not displayed on the chart. I must add three zeros at the end (look like this: 1346803200000), then the chart displays correctly. So I have code:
for ($i=0; $i < count($chart['Data']) ; $i++) {
$time = $chart['Data'][$i]['time'];
}
I need add to variable $time numeric 000 (three zeros at the end). I can not add it this way:
$time = $chart['Data'][$i]['time']."000";
because variable $time change from int to string. I must have $time in integer type. Is there any way to add three zeros without changing the variable type inside the loop ?
Not sure why you are doing this or if there is a better way, but if type conversion is the only thing that worries you, you can explicitly cast it to int:
$time = (int)($chart['Data'][$i]['time']."000");
Also, not sure if this is your desired behavior, but just note that your $time variable will get overwritten with every iteration of the for loop.
And one more thing, you can achieve your desired output without the explicit conversion by just multiplying your result with 1000, like so:
$time = $chart['Data'][$i]['time'] * 1000;
This should be a better solution than concatenation when you are working with ints
Seriously?
$time = $chart['Data'][$i]['time'] * 1000;
You con multiply for 1000
$time = $chart['Data'][$i]['time']*1000;

Php check if digit time is greater than other digit time

I have an array of digit time numbers (I get them from the input fields).
Here are a few examples:
00:00:10
00:03:00
01:20:00
My question is following, how do I check if a digit time is greater than another?
Following function works up to
00:01:00
After that I get an error.
$inputTimes = $request->input('times', []);
foreach ($inputTimes as $inputKey => $inputValue)
{
$Input = new Input();
$Input->input_start = $inputValue['input_start'];
$tInput = explode(':', $inputValue['input_timelapse']);
$implInput = implode('', $tInput);
$iImplInput = (int)$implInput;
// Check if time is greater
if($iImplInput > $iVideoDuration)
{
.. error time greater
}
}
I would convert it to Unix time by using the inbuild strtotime() function.
For example:
strtotime('01:20:00'); will output 1483492800 while strtotime('00:01:00'); will output 1483488060.
Hope this helped.

compare times with hundredths in php

I try to compare two swim times in php. They are like HH:MM:SS.XX (XX are hundreths). I get them as string and i want to find out which swimmer is faster. I tryed to convert them using strtotime(). It works with hours, minutes and seconds but it ignores hundreths. Here is my code for better explanation:
$novy = strtotime($input1);
$stary = strtotime($input2);
if($novy < $stary){
//change old(stary) to new(novy)
}
If $input1 is 00:02:14.31 and $input2 is 00:02:14.32 both $novy and $stary are 1392850934.
I read some solution to similar problem in javascript but I can`t use it, this must be server-side.
Thank you for help.
If you use date_create_from_format you can specify the exact date format for php to convert the string representations to:
<?php
$input1 = '00:02:14.31';
$input2 = '00:02:14.32';
$novy = date_create_from_format('H:i:s.u', $input1);
$stary = date_create_from_format('H:i:s.u',$input2);
if ($novy < $stary) {
echo "1 shorter\n";
} else {
echo "2 longer\n";
}
Recommended reading: http://ie2.php.net/datetime.createfromformat
If the format is really HH:MM:SS.XX (ie: with leading 0's), you can just sort them alphabetically:
<?php
$input1 = '00:02:14.31';
$input2 = '00:02:14.32';
if ($input1 < $input2) {
echo "1 faster\n";
} else {
echo "2 faster\n";
}
It prints 1 faster
You could write some conditional logic to test if HH::MM::SS are identical, then simply compare XX, else use the strtotime() function that you are already using
You are working with durations, not dates. PHP's date and time functions aren't really of any help here. You should parse the string yourself to get a fully numeric duration:
$time = '00:02:14.31';
sscanf($time, '%d:%d:%d.%d', $hours, $minutes, $seconds, $centiseconds);
$total = $centiseconds
+ $seconds * 100
+ $minutes * 60 * 100
+ $hours * 60 * 60 * 100;
var_dump($total);
The total is in centiseconds (100th of a second, the scale of your original input). Multiply/divide by other factors to get in others scales, as needed.

Check whether day is specified in a date string

Test case scenario - User clicks on one of two links: 2012/10, or 2012/10/15.
I need to know whether the DAY is specified within the link. I am already stripping the rest of the link (except above) out of my URL, am I am passing the value to an AJAX request to change days on an archive page.
I can do this in either JS or PHP - is checking against the regex /\d{4}\/\d{2}\/\d{2}/ the only approach to seeing if the day was specified or not?
You can also do this if you always get this format: 2012/10 or 2012/10/15
if( str.split("/").length == 3 ) { }
But than there is no guaranty it will be numbers. If you want to be sure they are numbers you do need that kind of regex to match the String.
You could explode the date by the "/" delimiter, then count the items:
$str = "2012/10";
$str2 = "2012/10/5";
echo count(explode("/", $str)); // 2
echo count(explode("/", $str2)); // 3
Or, turn it into a function:
<?php
function getDateParts($date) {
$date = explode("/", $date);
$y = !empty($date[0]) ? $date[0] : date("Y");
$m = !empty($date[1]) ? $date[1] : date("m");
$d = !empty($date[2]) ? $date[2] : date("d");
return array($y, $m, $d);
}
?>
I would personally use a regex, it is a great way of testing this sort of thing. Alternatively, you can split/implode the string on /, you will have an array of 3 strings (hopefully) which you can then test. I'd probably use that technique if I was going to do work with it later.
The easiest and fastest way is to check the length of the string!
In fact, you need to distinguish between: yyyy/mm/dd (which is 10 characters long) and yyyy/mm (which is 7 characters).
if(strlen($str) > 7) {
// Contains day
}
else {
// Does not contain day
}
This will work EVEN if you do not use leading zeros!
In fact:
2013/7/6 -> 8 characters (> 7 -> success)
2013/7 -> 6 characters (< 7 -> success)
This is certainly the fastest code too, as it does not require PHP to iterate over the whole string (as using explode() does).

PHP format date

How can I force the date format to output:
12/12/2012, 1/10/2012, 1/5/2012
instead of
12/12/2012, 01/10/2012, 01/05/2012?
My code is the following:
$adatefrom = date_create($_POST['datefrom']);
$adateto = date_create($_POST['adateto']);
$adatefrom = date_format($adatefrom, 'd/m/Y');
$adateto = date_format($adateto, 'd/m/Y');
Please do note that I have to format the date AFTER posting it.
Have a look at the PHP built in date function here
You will find that your solution is as simple as this:
date('j/n/Y',strtotime($_POST['datefrom']));
The key things to note are the characters used in the first parameter.
j represents the day without leading zeros
n represents the month without leading zeros
There are many other options you have, just have a read through the documentation.
Please note that a simple search of 'PHP date' on Google would have found this solution for you
$adatefrom = date_create($_POST['datefrom']);
$adateto = date_create($_POST['adateto']);
$adatefrom = date_format($adatefrom, 'j/n/Y');
$adateto = date_format($adateto, 'j/n/Y');
you are welcome! ;)

Categories