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.
Related
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";
}
Ok so I am working on a calendar application within my CRM system and I need to find the upper and lower bounds of the half an hour surrorunding the timestamp at which somebody entered an event in the calendar in order to run some SQL on the DB to determine if they already have something booked in within that timeslot.
For example I have the timestamp of 1330518155 = 29 February 2012 16:22:35 GMT+4
so I need to get 1330516800 and 1330518600 which equal 16:00 and 16:30.
If anyone has any ideas or think I am approaching developing the calendar in a stupid way let me know! Its my first time on such a task involving so much work with times and dates so any advice appreciated!
Use modulo.
$prev = 1330518155 - (1330518155 % 1800);
$next = $prev + 1800;
The modulo operator gives the remainder part of division.
I didn't read the questions clearly, but this code will round to the nearest half hour, for those who don't need the range between the two. Uses some of SenorAmor's code. Props and his mad elegant solution to the correct question.
$time = 1330518155; //Or whatever your time is in unix timestamp
//Store how many seconds long our rounding interval is
//1800 equals one half hour
//Change this to whatever interval to round by
$INTERVAL_SECONDS = 1800; //30*60
//Find how far off the prior interval we are
$offset = ($time % $INTERVAL_SECONDS);
//Removing this offset takes us to the "round down" half hour
$rounded = $time - $offset;
//Now add the full interval if we should have rounded up
if($offset > ($INTERVAL_SECONDS/2)){
$nearestInterval = $rounded + $INTERVAL_SECONDS;
}
else{
$nearestInterval = $rounded
}
You could use the modulo operator.
$time -= $time % 3600; // nearest hour (always rounds down)
Hopefully this is enough to point you in the right direction, if not please add a comment and I'll try to craft a more specific example.
PHP does have a DateTime class and a whole slough of methods that it provides. You could use these if you like, but I find it easier to use the built-in date() and strtotime() functions.
Here's my solution:
// Assume $timestamp has the original timestamp, i.e. 2012-03-09 16:23:41
$day = date( 'Y-m-d', $timestamp ); // $day is now "2012-03-09"
$hour = (int)date( 'H', $timestamp ); // $hour is now (int)16
$minute = (int)date( 'i', $timestamp ); // $minute is now (int)23
if( $minute < 30 ){
$windowStart = strtotime( "$day $hour:00:00" );
$windowEnd = strtotime( "$day $hour:30:00" );
} else {
$windowStart = strtotime( "$day $hour:30:00" );
if( ++$hour > 23 ){
// if we crossed midnight, fix the date and set the hour to 00
$day = date( 'Y-m-d', $timestamp + (24*60*60) );
$hour = '00';
}
$windowEnd = strtotime( "$day $hour:00:00" );
}
// Now $windowStart and $windowEnd are the unix timestamps of your endpoints
There are a few improvements that can be made on this, but that's the basic core.
[Edit: corrected my variable names!]
[Edit: I've revisited this answer because, to my embarrassment, I realized that it didn't handle the last half-hour of a day correctly. I've fixed that issue. Note that $day is fixed by adding a day's worth of seconds to the timestamp -- doing it this way means we don't have to worry about crossing month boundaries, leap days, etc. because PHP will format it correctly for us regardless.]
If you need to get the current time and then apply the rounding (down) of the time, I would do the following:
$now = date('U');
$offset = ($now % 1800);
$now = $now-$offset;
for ($i = 0;$i < 24; $i++)
{
echo date('g:i',$now);
$now += 1800;
}
Or you could round up by adding the offset, and do something more than just echo the time. The for loop then displays the 12 hours of increments. I used the above in a recent project.
I'd use the localtime and the mktime function.
$localtime = localtime($time, true);
$localtime['tm_sec'] = 0;
$localtime['tm_min'] = 30;
$time = mktime($localtime);
Far from my best work... but here's some functions for working with string or unix time stamp.
/**
* Takes a timestamp like "2016-10-01 17:59:01" and returns "2016-10-01 18:00"
* Note: assumes timestamp is in UTC
*
* #param $timestampString - a valid string which will be converted to unix with time()
* #param int $mins - interval to round to (ex: 15, 30, 60);
* #param string $format - the format to return the timestamp default is Y-m-d H:i
* #return bool|string
*/
function roundTimeString( $timestampString, $mins = 30, $format="Y-m-d H:i") {
return gmdate( $format, roundTimeUnix( time($timestampString), $mins ));
}
/**
* Rounds the time to the nearest minute interval, example: 15 would round times to 0, 15, 30,45
* if $mins = 60, 1:00, 2:00
* #param $unixTimestamp
* #param int $mins
* #return mixed
*/
function roundTimeUnix( $unixTimestamp, $mins = 30 ) {
$roundSecs = $mins*60;
$offset = $unixTimestamp % $roundSecs;
$prev = $unixTimestamp - $offset;
if( $offset > $roundSecs/2 ) {
return $prev + $roundSecs;
}
return $prev;
}
This is a solution using DateTimeInterface and keeping timezone information etc. Will also handle timezones that are not a multiple of 30 minutes offset from GMT (e.g. Asia/Kathmandu).
/**
* Return a DateTimeInterface object that is rounded down to the nearest half hour.
* #param \DateTimeInterface $dateTime
* #return \DateTimeInterface
* #throws \UnexpectedValueException if the $dateTime object is an unknown type
*/
function roundToHalfHour(\DateTimeInterface $dateTime)
{
$hours = (int)$dateTime->format('H');
$minutes = $dateTime->format('i');
# Round down to the last half hour period
$minutes = $minutes >= 30 ? 30 : 0;
if ($dateTime instanceof \DateTimeImmutable) {
return $dateTime->setTime($hours, $minutes);
} elseif ($dateTime instanceof \DateTime) {
// Don't change the object that was passed in, but return a new object
$dateTime = clone $dateTime;
$dateTime->setTime($hours, $minutes);
return $dateTime;
}
throw new UnexpectedValueException('Unexpected DateTimeInterface object');
}
You'll need to have created the DateTime object first though - perhaps with something like $dateTime = new DateTimeImmutable('#' . $timestamp). You can also set the timezone in the constructor.
Math.round(timestamp/1800)*1800
As you probably know, a UNIX timestamp is a number of seconds, so substract/add 1800 (number of seconds in 30 minutes) and you will get the desired result.
Here's a more semantic method for those that have to make a few of these, perhaps at certain times of the day.
$time = strtotime(date('Y-m-d H:00:00'));
You can change that H to any 0-23 number, so you can round to that hour of that day.
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);
}
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
I have a record returned from MySQL that has a datetime field. What I want to do is take this value and see if it is older then 24 hours, I presume using PHP's time() to get the current time.
At the moment if I echo them out I get:
1276954824 this is php's time()
2010-06-19 09:39:23 this is the MySQL datetime
I presume the top one is a unix time? Have been playing around with strtotime but with not much success..
ANy help welcome!
No success?
echo strtotime("2010-06-19 09:39:23");
gives me
1276940363
(mktime(9, 39, 23, 6, 19, 2010) gives the same time, so the parsing works correctly)
To get the differences in seconds, you can substract the timestamps, e.g.
$diff = time() - strtotime("2010-06-19 09:39:23");
If the differences is larger than 86400 (60*60*24) seconds, then the timestamps are more than one day apart:
if(time() - strtotime("2010-06-19 09:39:23") > 60*60*24) {
// timestamp is older than one day
}
You can also do:
SELECT * FROM my_table WHERE timestamp < NOW() - INTERVAL 1 DAY;
Why are you mixing PHP times and MySQL times?
Instead, do the comparison directly in MySQL:
To get the current date/time in MySQL use the NOW() function. You can compare, for example, 2010-06-19 09:39:23' < DATE_SUB(NOW(), INTERVAL 1 DAY)
This would check to see if the given date (presumably in a column) is older than 24 hours.
If it's absolutely necessary to convert a MySQL timestamp to a UNIX timestamp, you can use MySQL's UNIX_TIMESTAMP() function to do so.
I wrote a function, by which you can determine if the first given date is one day or n days bigger or smaller than the second given date.
$date1 = "2013/03/01";
$date2 = "2013/03/01";
$sign = "-";
$diff = 1;
$result = isDaysSmallerBigger($date1, $date2, $sign, $diff);
var_dump($result);
/**
* Note: this function is only supported in php 5.3 or above
* 1. If $date1 - $date2 = $sign $diff days, return true;
* 2. If $date1 equals $date2 and $diff euqals 0, whether $sign is "+" or "-", return true
* 3. Else return false;
* #param unknown_type $date1
* #param unknown_type $date2
* #param string $sign: "-": $date1 < $date2; "+": $date1 > $date2;
* Besides if $diff is 0, then both "-" and "+" means $date1 === $date2;
* #param integer $diff: date difference between two given dates
*/
function isDaysSmallerBigger($date1, $date2, $sign, $diff) {
$dateTime1 = new DateTime($date1);
$dateTime2 = new DateTime($date2);
$interval = $dateTime2->diff($dateTime1);
$dayDiff = $interval->format('%a');
$diffSign = $interval->format('%R');
if((int)$dayDiff === (int)$diff) {
// Correct date difference
if((int)$diff !== 0) {
// Day difference is not 0
if($diffSign === $sign) {
return true;
} else {
return false;
}
} else if((int)$diff === 0) {
// Day difference is 0, then both given "+" and "-" return true
return true;
}
} else {
// Incorrect date difference
return false;
}
}