How do i get the round values of system time in php? - php

I want to get round values of system time.
For example consider, now time is 6:02PM and I want to get the output as 6:05PM.
Is there any method???

You can use the ceil function with php:
$next_five = ceil(time()/300)*300;
this will give you the next round five minutes

$now = time();
$next_five = ceil($now/300)*300;
This will round up even if one second above a five minute mark
User below function
function blockMinutesRound($hour, $minutes = '5', $format = "H:i") {
$seconds = strtotime($hour);
$rounded = round($seconds / ($minutes * 60)) * ($minutes * 60);
return date($format, $rounded);
}
//call
blockMinutesRound('20:11');// return 20:10
Hope it helps ;)

Related

Time difference calculation in milliseconds in php

I Have a log reading program written in PHP. I want to calculate the time difference of any given two log lines.
I found lot of code for calculating the time difference if the two times are give like
$time1='10:15:30'; and $time2='10:15:35';. here the time difference will be 5 seconds.
But here my input times will be as in the following format
$time1='10:15:30:300'; and $time2='11:15:35:450';
I want a function which will receive this times as inputs and give the time difference in milliseconds.
Is there any inbuilt php function that can be utilized for this purpose ? or should we write our custom logic to split this time and then calculate the difference ?
My suggestion would be to find the difference in seconds first between the 2 times ignoring the milliseconds part.
So say, you have
$time1='10:15:30:300';
$time2='11:15:35:450';
In this case you will see that the seconds difference = 3605 seconds.
Now calculate the milliseconds difference and maybe format it as 3605.150
If the milliseconds difference is negative, reduce the second by 1.
Two functions which may help you with your time related development and calculations are the following
function find_time_diff($t1, $t2) {
$a1 = explode(":", $t1);
$a2 = explode(":", $t2);
$time1 = (($a1[0] * 60 * 60) + ($a1[1] * 60) + ($a1[2]));
$time2 = (($a2[0] * 60 * 60) + ($a2[1] * 60) + ($a2[2]));
$diff = abs($time1 - $time2);
return $diff;
}
and my favorite... this can return in minutes, days,years and so on
function find_date_diff($start_date, $end_date, $formatreturn = 'minutes') {
list($date, $time) = explode(' ', $start_date);
if ($time == null) {
$time = '00:00:00';
}
if ($date == null) {
$date = date("Y-m-d");
}
$startdate = explode("-", $date);
$starttime = explode(":", $time);
list($date, $time) = explode(' ', $end_date);
if ($time == null) {
$time = '00:00:00';
}
if ($date == null) {
$date = date("Y-m-d");
}
$enddate = explode("-", $date);
$endtime = explode(":", $time);
$secons_dif = mktime($endtime[0], $endtime[1], $endtime[2], $enddate[1], $enddate[2], $enddate[0]) - mktime($starttime[0], $starttime[1], $starttime[2], $startdate[1], $startdate[2], $startdate[0]);
switch ($formatreturn) {
//In Seconds:
case 'seconds':
$choice = $secons_dif;
break;
//In Minutes:
case 'minutes':
$choice = floor($secons_dif / 60);
break;
//In Hours:
case 'hours':
$choice = floor($secons_dif / 60 / 60);
break;
//In days:
case 'days':
$choice = floor($secons_dif / 60 / 60 / 24);
break;
//In weeks:
case 'weeks':
$choice = floor($secons_dif / 60 / 60 / 24 / 7);
break;
//In Months:
case 'months':
$choice = floor($secons_dif / 60 / 60 / 24 / 7 / 4);
break;
//In years:
case 'years':
$choice = floor($secons_dif / 365 / 60 / 60 / 24);
break;
}
$choice;
return $choice;
}
Try this function:
function mtime_difference($t1, $t2) {
$t1 = DateTime::createFromFormat('H:i:s:u', $t1, new DateTimezone('UTC'));
$t2 = DateTime::createFromFormat('H:i:s:u', $t2, new DateTimezone('UTC'));
$diff = $t2->diff($t1);
$seconds = $diff->h * 3600 + $diff->i * 60 + $diff->s;
$u = $t1->format('u') - $t2->format('u');
if ($u < 0) {
$seconds--;
$u = 1000000 - abs($u);
}
$u = substr(sprintf('%06d', $u), 0, 3);
return $seconds . '.' . $u;
}
echo mtime_difference('11:15:35:450', '10:15:30:300');
# 3605.150
demo
#Glavic - small typo in your method, this line:
$u = $t1->format('u') - $t2->format('u');
should be:
$u = $t2->format('u') - $t1->format('u');
At first, your times are written wrong. There should be decimal dot before milliseconds.
It means there will be times
10:15:30.300 and 11:15:35.450
instead
10:15:30:300 and 11:15:35:450
But in class written below you could improve pattern to it would fit your time formatting. Or change whole checking.
For similar case I had to solve very recently (reading of csv files created by smartphone/tablet app IoTools and counting milliseconds differences between times), and based on question How to get time difference in milliseconds, I prepared class that does it - but only within range of one day (24 hours).
It is not perfect (as it could get some more options) but it computes well (I hope that it does well, I have not tested it much).
For this answer, I deleted details of exceptions throwing and rewrote some constants by their values. Also I deleted annotations to make code shorter, but replaced them with descripting texts.
class DayTimeCount
{
Times are converted into milliseconds. So, these two variables may be typed as integer.
protected $Time_Start = 0;
protected $Time_End = 0;
Also time scale may be as integer. Name of this variable may be a bit unfortunate, as it is not fully correctly saying for what purpose it is used.
protected $Time_Scale = 1;
This variable could be a constant. Its content is not changed at all.
private $TimePattern = '/(?<Hours>[0-9]{2})\:(?<Minutes>[0-9]{2})\:(?<Seconds>[0-9]{2}).(?<Milliseconds>[0-9]{0,3})/';
This function is for setting of start time (time when starts interval you need to count). After checking if time is set in correct pattern (as string corresponding pattern writen above, not integer), time is converted into milliseconds.
public function Set_StartTime($Time = NULL)
{
try
{
if( !preg_match($this -> TimePattern, $Time, $TimeUnits) )
{
throw new Exception(/* some code */);
}
}
catch( Exception $Exception )
{
$Exception -> ExceptionWarning(/* some code */);
}
$this -> Time_Start = ($TimeUnits['Hours'] * 60 * 60 * 1000) + ($TimeUnits['Minutes'] * 60 * 1000) + ($TimeUnits['Seconds'] * 1000) + $TimeUnits['Milliseconds'];
}
This function is similar to previous, but for setting of end time (time when ends interval you need to count).
public function Set_EndTime($Time = NULL)
{
try
{
if( !preg_match($this -> TimePattern, $Time) )
{
throw new Exception(/* some code */);
}
}
catch( Exception $Exception )
{
$Exception -> ExceptionWarning(/* some code */);
}
$this -> Time_End = ($TimeUnits['Hours'] * 60 * 60 * 1000) + ($TimeUnits['Minutes'] * 60 * 1000) + ($TimeUnits['Seconds'] * 1000) + $TimeUnits['Milliseconds'];
}
This function is for setting of time scale. It helps to convert milliseconds to seconds (with precision of milliseconds) or minutes or hours.
Static function Check_IsTimeScale is my own function that works as in_array().
public function Set_TimeScale($Scale = 1)
{
try
{
if( !Core::Check_IsTimeScale($Scale) )
{
throw new Exception(/* some code */);
}
}
catch( Exception $Exception )
{
$Exception -> ExceptionWarning(/* some code */);
}
$this -> Time_Scale = $Scale;
}
And finally, function is for own counting of time difference. It has only three steps.
public function Execute()
{
The first one is own counting. If difference between end and start is positive number (greater than zero), it is taken as it is.
But if difference between end and start is negative (as end is after midnight and start is before midnight, for example 00:00:00.658 and 23:59:59:354), then it is needed to use additional counting. To make difference between start and full time of day - and add end time.
$Diff = $this -> Time_End - $this -> Time_Start;
if( $Diff < 0 )
{
$Diff = $this -> Time_End + (86400000 - $this -> Time_Start);
}
The second step, application of time scale. Time in milliseconds is divided by time scale. If it is divided by 1, result is (of course) the same as original number and it is no rounded. If it is divided by larger number (1000 or greater from allowed options), it is rounded to length of number used to divide it.
$Diff = round($Diff / $this -> Time_Scale, strlen($this -> Time_Scale));
Third step is returning of final result. Probably it could be merged with previous step, but now it is (at least) better readable.
return $Diff;
}
}
Function ExceptionWarning is also my function, and can be replaced by your own one.

mysql convert decimal time to xx:xx format

I am trying to convert a decimal time into an actual time format with hours and minutes, ie: in xx:xx hours.
My query is:
select SUM(vt.vluchtdec) AS vluchttijddecimal
from tbl_vluchtgegevens vg
left join tbl_vluchttijd vt
on vg.vluchttijddec = vt.vluchttijdID
WHERE vg.vertrekdatum <=NOW();
And I am echoing
. $row['vluchttijddecimal'] .
I have also tried this, but this also still gives me my response in a decimal format:
$result = mysql_query("select SUM(vt.vluchtdec) AS vluchttijddecimal
from tbl_vluchtgegevens vg
left join tbl_vluchttijd vt
on vg.vluchttijddec = vt.vluchttijdID
WHERE vg.vertrekdatum <=NOW();");
while($row = mysql_fetch_array($result))
{
$dec = $row['vluchttijddecimal'];
function
convertTime($dec)
{
// start by converting to seconds
$seconds = $dec * 3600;
// we're given hours, so let's get those the easy way
$hours = floor($dec);
// since we've "calculated" hours, let's remove them from the seconds variable
$seconds -= $hours * 3600;
// calculate minutes left
$minutes = floor($seconds / 60);
// remove those from seconds as well
$seconds -= $minutes * 60;
// return the time formatted HH:MM:SS
return lz($hours).":".lz($minutes).":".lz($seconds);
}
// lz = leading zero
function lz($num)
{
return (strlen($num) < 2) ? "0{$num}" : $num;
}
echo "" .$dec."";
In MS Access I would do something like this:
CInt([vluchttijddecimal]) & ":" & Format([vluchttijddecimal]*60 Mod 60;"00")
But this does not work or I don't know how to do so in MySQL / php.
For anyone that is interested... This is how you would convert decimal time (Where 0.1 == 6 minutes) to hours and minutes (0.2333 == 14 minutes) in MYSQL alone. no PHP is needed. This also accounts for the need to round seconds to minutes.
SELECT CONCAT(FLOOR(timeInDec),':', LPAD(ROUND((timeInDec - FLOOR(timeInDec)) * 60) % 60,2,0)) AS TimeInHoursMinutes
FROM YourTable;
Replace timeInDec with the column name that contains the decimal time you would like to convert.
This will return 0:06 for 0.1000 decimal value so leading zeros are accounted for in single digit minutes.
You can do this in you SQL statement something like this:
SELECT CONCAT(CEIL(mydecimal),':', LPAD(Floor(mydecimal*60 % 60),2,'0')) as formated text
Where mydecimal is your unformatted field name
I think I have calculated your time values... although it was kinda pain.
It appears your "decimal time" is "hours.minutes"? Rather horrible and definitely not a good format: for dealing with time its best to stick to integers that specify either a total of minutes/seconds/hours or whatever granularity you need.
But assuming it is hours.minutes, you should be able to do it like this in PHP:
while($row = mysql_fetch_array($result))
{
$dec = $row['vluchttijddecimal'];
return sprintf("%2d:%2d", floor($dec), floor(($dec - floor($dec))*100));
}
Hopefully I am correct in assuming that you mean, for example that 2.5 hours = 2H 30mins. If so, then your 'time' is a time interval and is best represented by the DateInterval class.
This function will do what you want:-
/**
* Converts a 'decimal time' in the format 1.5hours to DateInterval object
*
* #param Int $decimalTime
* #return DateInterval
*/
function decTimeToInterval($decimalTime)
{
$hours = floor($decimalTime);
$decimalTime -= $hours;
$minutes = floor($decimalTime * 60);
$decimalTime -= ($minutes/60);
$seconds = floor($decimalTime * 3600);
$interval = new \DateInterval("PT{$hours}H{$minutes}M{$seconds}S");
return $interval;
}
echo decTimeToInterval(512.168)->format("%H:%I:%S");
See it working
If you want to add times in the format 'H:i' without converting them to and from decimals, you can do it like this:-
function sumTimes($time1, $time2)
{
list($hours1, $minutes1) = explode(':', $time1);
list($hours2, $minutes2) = explode(':', $time2);
$totalHours = $hours1 + $hours2;
$totalMinutes = $minutes1 + $minutes2;
if($totalMinutes >= 60){
$hoursInMins = floor($totalMinutes/60);
$totalHours += $hoursInMins;
$totalMinutes -= ($hoursInMins * 60);
}
return "$totalHours:$totalMinutes";
}
echo sumTimes('12:54', '100:06') . PHP_EOL;
echo sumTimes('12:54', '100:20') . PHP_EOL;
See it working
This is what I used for my Payroll System:
SELECT If(total_late>0, LPAD(CONCAT(REPLACE(FLOOR(total_late/60) + FORMAT(total_late%60*0.01,2), '.', ':'), ':00'), 8, 0), '00:00:00') FROM MyTable
I multiplied it by 0.01 because my variables are in Seconds. Eg. 60.00 = 1min
I would suggest this to include seconds. It is based on #Richard's solutions. Just notice I've changed CEIL by FLOOR in #Richard's solution.
SET #timeInDec=1.505;
SELECT CONCAT(FLOOR(#timeInDec),':', LPAD(FLOOR(#timeInDec*60 % 60),2,'0'),':', LPAD(FLOOR(MOD(#timeInDec*60 % 60,1)*100),2,0)) as timeInDec;

php - calculating distance divded by time

How do I divide a decimal by time queried from database as time format.
Any idea?
$time = date($entity->getTime()->format('H:i:s'));
$speed = $distance/$time
Which is definitely wrong and if my time is 00:40:00, I get some division by zero error.
I am unable to convert it to seconds because php takes DateTime from Time format in database.
I propose that you get your time in seconds, but you need to convert minutes and hours to seconds.
$seconds = date($entity->getTime()->format('s'));
$minutes = date($entity->getTime()->format('i'));
$hours = date($entity->getTime()->format('h'));
$time = $hours * 3600 + $minutes * 60 + $seconds;
$speed = $distance/$time;
Checkout strtotime() to convert it to seconds.
Docs: http://php.net/manual/en/function.strtotime.php
With strtotime it is a little bit tricky and only goes to 24:59:59.
Else use Voitcus solution.
$time = '00:40:00';
echo strtotime("1970-01-01 $time UTC");
1) Get time in seconds
function time2seconds($time='00:00:00')
{
list($hours, $mins, $secs) = explode(':', $time);
return ($hours * 3600 ) + ($mins * 60 ) + $secs;
}
$time = date($entity->getTime()->format('H:i:s'));
$timeInSeconds = time2seconds($time);
$distance = 40000;
$speed = $distance/$timeInSeconds;
2) If you are using MySQL database use function TIME_TO_SEC(time)
$time = date($entity->getTime()->format('H:i:s'));
$speed = $distance/$time
It's wrong. You must do:
$speed = $distance/$time * 3.6;
For instance this equation is valid 30km/H = 30000m * 3600 seconds * 3.6

How to convert a decimal into time, eg. HH:MM:SS

I am trying to take a decimal and convert it so that I can echo it as hours, minutes, and seconds.
I have the hours and minutes, but am breaking my brain trying to find the seconds. Been googling for awhile with no luck. I'm sure it is quite simple, but nothing I have tried has worked. Any advice is appreciated!
Here is what I have:
function convertTime($dec)
{
$hour = floor($dec);
$min = round(60*($dec - $hour));
}
Like I said, I get the hour and minute without issue. Just struggling to get seconds for some reason.
Thanks!
If $dec is in hours ($dec since the asker specifically mentioned a decimal):
function convertTime($dec)
{
// start by converting to seconds
$seconds = ($dec * 3600);
// we're given hours, so let's get those the easy way
$hours = floor($dec);
// since we've "calculated" hours, let's remove them from the seconds variable
$seconds -= $hours * 3600;
// calculate minutes left
$minutes = floor($seconds / 60);
// remove those from seconds as well
$seconds -= $minutes * 60;
// return the time formatted HH:MM:SS
return lz($hours).":".lz($minutes).":".lz($seconds);
}
// lz = leading zero
function lz($num)
{
return (strlen($num) < 2) ? "0{$num}" : $num;
}
Very simple solution in one line:
echo gmdate('H:i:s', floor(5.67891234 * 3600));
Everything upvoted didnt work in my case.
I have used that solution to convert decimal hours and minutes to normal time format.
i.e.
function clockalize($in){
$h = intval($in);
$m = round((((($in - $h) / 100.0) * 60.0) * 100), 0);
if ($m == 60)
{
$h++;
$m = 0;
}
$retval = sprintf("%02d:%02d", $h, $m);
return $retval;
}
clockalize("17.5"); // 17:30
I am not sure if this is the best way to do this, but
$variabletocutcomputation = 60 * ($dec - $hour);
$min = round($variabletocutcomputation);
$sec = round((60*($variabletocutcomputation - $min)));
This is a great way and avoids problems with floating point precision:
function convertTime($h) {
return [floor($h), (floor($h * 60) % 60), floor($h * 3600) % 60];
}

How to find time difference between 2 time vars greater than 24 hours

I need to find how much time is between to time values (their difference) which are over 24:00:00.
For example: how can I calculate the difference between 42:00:00 and 37:30:00?
Using strtotime, strptotime, etc is useless since they cannot go over 23:59:59 ....
$a_split = explode(":", "42:00:00");
$b_split = explode(":", "37:30:00");
$a_stamp = mktime($a_split[0], $a_split[1], $a_split[2]);
$b_stamp = mktime($b_split[0], $b_split[1], $b_split[2]);
if($a_stamp > $b_stamp)
{
$diff = $a_stamp - $b_stamp;
}else{
$diff = $b_stamp - $a_stamp;
}
echo "difference in time (seconds): " . $diff;
then use date() to convert seconds to HH:MM:SS if you want.
Date/Time variables and functions are not appropriate here as you're not storing time, but instead a time span of (I assume) hours, minutes, and seconds.
Likely your best solution is going to be to split each time span into their integer components, convert to a single unit (for instance, seconds), subtract them from each other, then re-build an output time span that fits with your application.
I havent tested this, but this might do what you want:
function timediff($time1, $time2) {
list($h,$m,$s) = explode(":",$time1);
$t1 = $h * 3600 + $m * 60 + $s;
list($h2,$m2,$s2) = explode(":",$time2);
$seconds = ($h2 * 3600 + $m2 * 60 + $s2) - $t1;
return sprintf("%02d:%02d:%02d",floor($seconds/3600),floor($seconds/60)%60,$seconds % 60);
}

Categories