Php check if digit time is greater than other digit time - php

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.

Related

Get duration using YouTube API

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;
}

PHP Convert Minutes+Seconds to Seconds

Currently, I have the following time format like the following:
0m12.345s
2m34.567s
I put them in variable $time. How do I convert the variable to seconds only in PHP, like 12.345 for the first one, and 154.567 for the second one?
You can do it like this,
//Exploding time string on 'm' this way we have an array
//with minutes at the 0 index and seconds at the 1 index
//substr function is used to remove the last s from your initial time string
$time_array=explode('m', substr($time, 0, -1));
//Calculating
$time=($time_array[0]*60)+$time_array[1];
<?php
$time="2m34.567s";
$split=explode('m',$time);
// print_r($split[0]);
$split2=explode('s',$split[1]);
$sec= seconds_from_time($split[0])+$split2[0];
echo $sec;
function seconds_from_time($time) {
return $time*60;
}
?>
Demo here http://phpfiddle.org/main/code/gdf-3tj

preg_match to find a word that ends in a certain character

I am trying to make a small program that searches within a timer (with this format 00d 00h 00m 00s) and returns the days into one variable, the hours into another, etc.
This is some of my code:
$time1 = "Left: 11d 21h 50m 06s <\/div>"
preg_match_all("/ .*d/i", $time1, $timematch); // Day
$time1day = $timematch[1]; // Saves to variable
preg_match_all("/ .*h/i", $time1, $timematch); // Hour
$time1hour = $timematch[1]; // Saves to variable
preg_match_all("/ .*m/i", $time1, $timematch); // Minute
$time1minute = $timematch[1]; // Saves to variable
preg_match_all("/ .*s/i", $time1, $timematch); // Second
$time1second = $timematch[1]; // Saves to variable
My regex isn't correct but I'm not sure what it should be. Any ideas?
By the way, I am using PHP4.
This regex will do the trick:
(\d+)d (\d+)h (\d+)m (\d+)s
Each value (day, hour, minute, second) will be captured in a group.
About your regex: I don't know what do you mean by "isn't correct", but I guess it's probably failing because your regex is greedy instead of lazy (more info). Try using lazy operators, or using more specific matches (\d instead of ., for example).
EDIT:
I need them to be separate variables
After matching, they will be put in different locations in the resulting array. Just assign them to variables. Check out an example here.
If you have trouble understanding the resulting array structure, you may want to use the PREG_SET_ORDER flag when calling preg_match_all (more information here).
If the format is always in the order you show, I wouldn't regex it. The following should get your job done:
$time1= "Left: 11d 21h 50m 06s <\/div>";
$timeStringArray = explode(" ",$timeString);
$time1day = str_replace("d","",$timeStringArray[1]);
$time1hour = str_replace("h","",$timeStringArray[2]);
$time1minute = str_replace("m","",$timeStringArray[3]);
$time1second = str_replace("s","",$timeStringArray[4]);
If the pattern is always this, two digits plus the time letter, you can do this:
$time1 = "Left: 11d 21h 50m 06s <\/div>";
preg_match_all("/(\d{2})[dhms]/", $time1, $match);
print_r($match);
UPDATE: this function can work with 1 or 2 digits, and match all the params.
$time1 = "Left: 11d 21h 50m 06s <\/div>";
$time2 = "Left: 21h 50m 5s";
$time3 = "Left: 9m 15s";
function parseTime($str) {
$default = array('seconds', 'minutes', 'hours', 'days');
preg_match_all("/(\d{1,2})[dhms]/", $str, $time);
if (!isset($time[1]) || !is_array($time[1])) {
return null;
}
$default = array_slice($default, 0, count($time[1]));
return array_combine($default, array_reverse($time[1]));
}
print_r(parseTime($time1));
print_r(parseTime($time2));
print_r(parseTime($time3));

range() issuing a warning when date_diff is used

The following script issues a
'Warning: range() [function.range]: step exceeds the specified range in'
only when the date_diff function is called. Does anyone know why?
<?php
$array = array(
"Interno",
"id"
);
$step = count($array) - 1;
foreach (range(0, $step) as $number) {
echo '<p>'.$number.'</p>';
}
$datetime1 = new DateTime('2010-08-2');
$datetime2 = new DateTime('2009-07-30');
$interval = date_diff($datetime1,$datetime2);
?>
Well, the two functions have nothing to do with each other.
Secondly, the second parameter to range is not a step, it's a maximum value (see the range docs... So if you're getting a step exceeds the specified range error, I'd guess that the default step value 1 is larger than the max of the range (the result of count($array) - 1)... I'm not sure why that's happening in your code, but it's a start
That's a PHP bug.
Still present as of 5.3.5, it seems that was fixed in 5.3.6.
https://bugs.php.net/bug.php?id=51894
I do agree with ircmaxell, function range and date_diff are not related and do not interact in any way. The issue should be in your array which get altered in some way.
Also, as for me, your example contain unnecessary operations like count and range and it could be shortened to this:
<?php
$array = array(
"Interno",
"id"
);
foreach ($array as $number => $value) {
echo '<p>'.$number.'</p>';
}
$datetime1 = new DateTime('2010-08-2');
$datetime2 = new DateTime('2009-07-30');
$interval = date_diff($datetime1,$datetime2);
?>

Imprecise numbers with microtime and floating point addition in PHP

I'm having a terrible time convincing myself what I've done here is a good idea. The specific section I find objectionable is:
return ((float)($now+$sec).'.'.$mic);
In order to preserve the floating point precision, I'm forced to either fall back on the BC or GMP libraries (neither of which is always available). In this case, I've resorted to jamming the numbers together with string concatenation.
<?php
// return the current time, with microseconds
function tick() {
list($sec, $mic, $now) = sscanf(microtime(), "%d.%d %d");
return ((float)($now+$sec).'.'.$mic);
}
// compare the two given times and return the difference
function elapsed($start, $end) {
$diff = $end-$start;
// the difference was negligible
if($diff < 0.0001)
return 0.0;
return $diff;
}
// get our start time
$start = tick();
// sleep for 2 seconds (should be ever slightly more than '2' when measured)
sleep(2);
// get our end time
$end = tick();
$elapsed = elapsed($start, $end);
// should produce output similar to: float(2.00113797188)
var_dump($elapsed);
?>
If I attempt to add two numbers like 123456789 (representing a timestamp) and 0.0987654321 (representing microseconds), using the addition operator (+) I invariably end up with 123456789.099. Even when casting the integer to float, the result is the same.
Is there a solution for this issue which is 1) not a hack and 2) doesn't involve string concatenation? I shouldn't have to fall back on this sort of garbled code in order to get an accurate timestamp with microsecond resolution.
Edit: As S. Gehrig has explained, floating point numbers in PHP can be, at times, a bit tricky to display. The "precision" indicated in the PHP configuration is regarding display. The actual values are not rounded like I thought. A far simpler solution to the above code would look like so:
// return the current time, with microseconds
function tick() {
return microtime(true);
}
// compare the two given times and return the difference
function elapsed($start, $end) {
return $end-$start;
}
// get our start time
$start = tick();
// sleep for 2 seconds (should be ever slightly more than '2' when measured)
sleep(2);
// get our end time
$end = tick();
$elapsed = elapsed($start, $end);
// should produce output similar to: float(2.00113797188)
var_dump($elapsed);
If you were to examine $start or $end before subtracting one from the other, it might appear they were rounded to the hundredths position. This is not the case. It seems arbitrary precision is maintained for arithmetic while the display is limited.
Why don't you use microtime(true) which simply returns a microsecond timestamp as float? The parameter [bool] $get_as_float was added in PHP 5.0.0.
Regarding the comment about the "loss" of precision:
$start = microtime(true);
$end = microtime(true);
echo $end - $start;
// prints 7.1526861190796
microtime(true) is not limited to 2 decimal places. What the poster encounters is the effect of the configuration setting precision which controls how many decimal places will be printed when outputting float variables. This has nothing to do with the internal precision microtime(true) uses. You can always use number_format() or (s)printf() to format the output to the precision you like.
First, spligak, I see that your code contains an error.
list($sec, $mic, $now) = sscanf(microtime(), "%d.%d %d");
return ((float)($now+$sec).'.'.$mic);
If $mic has fewer than six digits, you get garbage results. Do a desk check on
the case where microtime() returns "0.000009 1234567890"
Second, you can greatly reduce the floating-point error as follows:
(WARNING: untested code!)
// compare the two given times and return the difference
// get our start time
$start = microtime();
// sleep for 2 seconds (should be ever slightly more than '2' when measured)
sleep(2);
// get our end time
$end = microtime();
// work around limited precision math
// subtract whole numbers from whole numbers and fractions from fractions
list($start_usec, $start_sec) = explode(" ", $start);
list($end_usec, $end_sec) = explode(" ", $end);
$elapsed = ((float)$end_usec)-((float)$start_usec);
$elapsed += ((float)$end_sec)-((float)$start_sec);
// please check the output
var_dump($elapsed);
Floating point types are inherently imprecise. Either live with it, or don't use them.

Categories