Time(only & not date) comparison - php

I need to compare two different times. Both of the format:
Hour:Min:Sec
None of them is picked up from current time. So, no strtotime or DateTime. I don't want the date to be involved in any way in the comparison.
Every question here ends with strtotime as the answer.
What I want is to compare these two times out of which one is getting picked from DataBase(is of the type time) & one I'm manually giving as string.
For eg: $A="00:00:00"(if can be stored otherwise kindly do tell).
If there is any way to do this,kindly do tell me?Thnxx in advance...

You could use a function that convert your times into seconds and then do a comparison based on the results
function getTimeInSeconds($hours, $minutes, $seconds) {
$totalSeconds = 0;
//Add the numner of hours in seconds
$totalSeconds += ($hours * 60) * 60;
//Add the number of minutes in seconds
$totalSeconds += $minutes * 60;
//Add seconds
$totalSeconds += $seconds;
return $totalSeconds;
}
$firsttime = getTimeInSeconds(8, 30, 14);
$secondtime = getTimeInSeconds(10, 15, 06);
//If second time is later than first time
if($secondtime > $firsttime)
{
}
//If first time is later than second time
if($firsttime > $secondtime)
{
}

If time is in 24 hour format you can simply compare it by string comparison
$A="00:00:00"
$B="13:00:00"
if ($A > $B) {
// do stuff
}

if you don't want to use strtotime or DateTime i'm not sure it will gives you correct output cause it will be compare as a string or int values so not possible to calculate exact time so better to use php date and time functions
For eg: $A="00:00:00" (it will be a string value)
so better output will be convert both values using strtotime() and do your stuff

You could just multiply out the seconds and compare them.
$timebits = explode(':',$A);
$secondsDB = $timebits[2] + timebits[1]*60 + $timebits[0]*60*60
and then compare to your manual time in seconds.

You can use CAST( ) function in mysql query
SELECT * FROM table_name WHERE yourcolumn < CAST('05:00:00' AS time)

If you require to compare if times on format HH:MM:SS are equal or if one is before another and don't want to use strtotime function you should convert all to seconds and compare as numbers.
Simple example:
$a="01:30:08";
$b="02:20:50";
function toseconds($str){
$array = explode(":",$str);
$val = $array[0] * 24 * 60;
$val += $array[1] * 60;
$val += $array[2];
return $val;
}
print toseconds($a); // print a
print " compare to ";
print toseconds($b); // print b
print " ";
if($a > $b){
print "b is before a";
}else if ($b > $a){
print "a is before b";
}else if($b == $a){
print "a and b are the same time";
}

Related

Sum of Duration from Database Field (Duration)

I am having issue in SUM of Time or Duration from my Database field.
Suppose. I have 5 Records
1. 00:25:32
2. 00:08:52
3. 00:33:22
4. 00:25:30
5. 00:15:12
how to sum all the times with php.
I spent a lot time on it but failed.
I have tried this.
$time = "00:58:30";
$time2 = "00:12:35";
$secs = strtotime($time2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($time)+$secs);
echo $result;
But it not works good for multiple records
Thanks to all of you. I have fixed it. I checked some other question on Stackoverflow and i got answer what i wanted.
SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(`SongDuration`))) AS `TimeSum` FROM `mu_forms_competition_entries`
Durations are not dates. What would tomorrow at 35:00:00 mean?
The closest builtin feature is DateInterval, but in order to use it as-is your input data needs some rewriting ('00:25:32' into 'PT00H25M32S') and I don't think it supports addition anyway.
It isn't difficult to make the calculations yourself (error checking omitted and negative times not considered for brevity):
function timeToSeconds(string $time): int
{
[$h, $m, $s] = explode(':', $time);
return $s + 60 * $m + 3600 * $h;
}
function secondsToTime(int $seconds): string
{
return sprintf(
"%02d:%02d:%02d",
floor($seconds / 3600),
floor(($seconds / 60) % 60),
$seconds % 60
);
}
$times = [
'00:25:32',
'00:08:52',
'00:33:22',
'00:25:30',
'00:15:12',
];
$total = 0;
foreach ($times as $time) {
$total += timeToSeconds($time);
}
echo secondsToTime($total);
If you're allowed to change the database query there's probably a builtin function to convert to seconds right from SQL. For instance, MySQL has TIME_TO_SEC().
Last but not least, if your database actually has a Time column type, perhaps it allows to SUM() it.

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;

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

Convert time to seconds

What the best way to convert 24 hours time to seconds so it can be used for comparison if statement..
function HourMinuteToDecimal($hour_minute) {
$t = explode(':', $hour_minute);
return $t[0] * 60 + $t[1];
}
echo HourMinuteToDecimal("23:30");
return 1410
If you try to convert midnight time (00:00) to seconds, it will not work. What is the solution to this?
00:00, 00:30, 01:00, 01:30, etc.
if (HourMinuteToDecimal("01:30") > HourMinuteToDecimal("23:30")) { .. }
This will not work.
PHP5.3
$formattedTime = '00:01:38';
$seconds = strtotime('1970-01-01 ' . $formattedTime . 'GMT')
To convert function:
function hoursToSecods ($hour) { // $hour must be a string type: "HH:mm:ss"
$parse = array();
if (!preg_match ('#^(?<hours>[\d]{2}):(?<mins>[\d]{2}):(?<secs>[\d]{2})$#',$hour,$parse)) {
// Throw error, exception, etc
throw new RuntimeException ("Hour Format not valid");
}
return (int) $parse['hours'] * 3600 + (int) $parse['mins'] * 60 + (int) $parse['secs'];
}
Write on the fly, no tested :-P
so, you can use strtotime to convert the format date in unix timestamp and comparte using a standar operators (== < > >= <= !=, etc) ex:
$t1 = "23:40:12";
$t2 = "17:53:04";
$h1 = strtotime("0000-00-00 $t1");
$h2 = strtotime("0000-00-00 $t2");
$h1 == $h2; // if are equals
$h1 > $h2; // if h1 is mayor at h2
$h1-$h2; // dieference in seconds, etc.
etc..
You seem to be asking contradicting things.
You want to convert a time in HH:MM into seconds.
But then you want to "compare" the result from different times, as if they had dates attached.
If you want to allow HourMinuteToDecimal("01:30") > HourMinuteToDecimal("23:30") to be true without a date, then, well, any comparison will return true.
If you want to do this properly, include the date (YYYY-MM-DD HH:MM:SS) and use strtotime in PHP to get the number of seconds since the UNIX epoch.
Also, your function returns minutes, not seconds.
You can compare objects of type time using the standard <, >, == operators. Use strtotime to convert the string to time, then compare.

How to compare two time in PHP

I had two times in the format like 7:30:00 and 22:30:00 stored in the variables $resttimefrom and $resttimeto respectively.
I want to check whether the current time is between these two values. I am checking this with the code
$time = date("G:i:s");
if ($time > $resttimefrom and $time < $resttimeto ){
$stat = "open";
} else {
$stat = "close";
}
But I am always getting the $stat as Close. What may cause that?
you can try using strtotime
$st_time = strtotime($resttimefrom);
$end_time = strtotime($resttimeto);
$cur_time = strtotime(now);
then check
if($st_time < $cur_time && $end_time > $cur_time)
{
echo "WE ARE CLOSE NOW !!";
}
else{
echo "WE ARE OPEN NOW !!";
}
i hope this may help you..
A simple yet smart way to do this is to remove the ':' from your dates.
$resttimefrom = 73000;
$resttimeto = 223000;
$currentTime = (int) date('Gis');
if ($currentTime > $resttimefrom && $currentTime < $resttimeto )
{
$stat="open";
}
else
{
$stat="close";
}
$today = date("m-d-y ");
$now = date("m-d-y G:i:s");
if (strtotime($today . $resttimefrom) < $now && $now > strtotime($today . $resttimeto)) {
$stat = 'open';
else
$stat = 'close
Try reformatting them into something that you can compare like that. For example, numbers:
$resttimefrom = mktime(7,30,0);
$resttimeto = mktime(22,30,0);
$time = mktime(date('H'),date('i'),date('s'));
You are comparing strings.
Convert the Time Strings to timestamps with strtotime().
Then compare against time().
Just convert your dates to a Unix Timestamp, compare them, you have your results! It might look something like this:
$time =date("G:i:s");
$time1 = strtotime($time);
$resttimefrom1 = strtotime($resttimefrom );
$resttimeto1 = strtotime($resttimeto );
if ($time1 >$resttimefrom and $time1 <$resttimeto)
{
$stat="open";
}
else
{
$stat="close";
}
The date function returns a string, so the comparison you're making would be a string comparison - so 7:30 would be more than 22:30
It would be much better to use mktime, which will return a Unix timestamp value (integer) so it would make for a better comparison
$currentTime = mktime();
$resttimefrom = mktime(hour,min,second);
http://php.net/mktime
The trick to manipulating and comparing dates and times in PHP is to store date/time values in an integer variable and to use the mktime(), date() and strtotime() functions. The integer repesentation of a date/time is the number of seconds since midnight, 1970-Jan-1, which is referred to as the 'epoch'. Once your date/time is in integer form you'll be able to efficiently compare it to other dates that are also in integer form.
Of course since you'll most likely be receiving date/time values from page requests and database select queries you'll need to convert your date/time string into an integer before you can do any comparison or arithmetic.
Assuming you are sure that the $resttimefrom and $resttimeto variables contain properly formatted time you can use the strtotime() function to convert your string time into an integer. strtotime() takes a string that is formatted as a date and converts it to the number of seconds since epoch.
$time_from = strtotime($resttimefrom);
$time_to = strtotime($resttimeto);
Side note: strtotime() always returns a full date in integer form. If your string doesn't have a date, only a time, strtotime() return today's date along with the time you gave in the string. This is not important to you, though, because the two dates returned by strtotime() will have the same date and comparing the two variables will have the desired effect of comparing the two times as the dates cancel each other out.
When you compare the two integers keep in mind that the earlier the date/time is, the smaller its integer value will be. So if you want to see if $time_from is earlier than $time_to, you would have this:
if ($time_from < $time_to)
{
// $time_from is ealier than $time_to
}
Now to compare a date/time with the current system date/time, just use mktime() with no parameters to represent the current date/time:
if ($time_from < mktime())
{
// $time_from is in the past
}
$firstTime = '1:07';
$secondTime = '3:01';
list($firstMinutes, $firstSeconds) = explode(':', $firstTime);
list($secondMinutes, $secondSeconds) = explode(':', $secondTime);
$firstSeconds += ($firstMinutes * 60);
$secondSeconds += ($secondMinutes * 60);
$difference = $secondSeconds - $firstSeconds;
$Time1 = date_parse($time);
$seconds1 = $Time1['hour'] * 3600 + $Time1['minute'] * 60 + $Time1['second'];
$Time2 = date_parse($current_time);
$seconds2 = Time2['hour'] * 3600 + Time2['minute'] * 60 + Time2['second'];
$actula_time = $seconds1 - $seconds2;
echo floor($actula_time / 3600) .":". floor(($actula_time / 60)%60) .":". $actula_time%60;
As Col. Shrapnel Said i am doing by converting all the time in to seconds and then compare it with current time's total seconds

Categories