Mysql table for hours(field type time):
opened closed
12:00:00 23:59:00
In php i need to check if the current time is between these two times.
FIrst i have converted php current server time into mysql time format
$cur_time = date('H:m A',$_SERVER['REQUEST_TIME']);
$cur_time = DateTime::createFromFormat( 'H:i A',$cur_time);
$cur_time = $cur_time->format('H:i:s');
Then i have compared the times-
if($cur_time > $biz_hours['opened'] && $cur_time < $biz_hours['closed'])
Note: $biz_hours is the array to fetch data from mysql table.
Printing the $cur_time is displaying 09:12:00 just now. But if caluse returning false. Here is the live site url: http://dsbangladesh.com/takeout-banani/b/10 . Please help me to find the problem.
The comparison you are using is a simple string comparison. Your best bet is to convert your data into timestamps first. Something like this:
$curTime = time();
$openTime = strtotime($biz_hours['opened']);
$closeTime = strtotime($biz_hours['closed']);
if($curTime > $openTime && $curTime < $closeTime)
{ ....
I've used time to get the current server time instead of the method you used. I've also used strtotime to convert the mysql time field into a timestamp.
if (time() > strtotime($biz_hours['opened']) && time() < strtotime($biz_hours['closed']))
<?php
$biz_o = new DateTime(date('H:i:s',strtotime($biz_hours['opened'])));
$biz_c = new DateTime(date('H:i:s',strtotime($biz_hours['closed'])));
$now = new DateTime(date('H:i:s'),strtotime($_SERVER['REQUEST_TIME']));
if($now > $biz_o && $now < $biz_c){
//You got me
}
Related
I am displaying a number of dates using PHP and I need to hide them when a certain date has expired.
I am using an IF statement to run this but it doesn't seem to be working.
Any suggestions would be great
<?PHP if('09-19-2016'<DATE('m-d-Y') || $_SESSION['role'] == 'Administrator') echo('<li>Week 2 - W/C 12/09/2016</li>');?>
When you're doing
'09-19-2016' < date('m-d-Y')
You're ending up comparing two strings, these can't be evaluated as "greater than" or "less than". You'll need to convert it to timestamps or use DateTime objects to do it. Also, the date format isn't correct.
<?php
$date_string = "09/19/2016";
// Using objects
$current_date = new DateTime();
$your_date = new DateTime($date_string);
if ($your_date < $current_date || $_SESSION['role'] == 'Administrator')
echo'<li>Week 2 - W/C 12/09/2016</li>';
// Using timestamps
if (strtotime($date_string) < time() || $_SESSION['role'] == 'Administrator')
echo'<li>Week 2 - W/C 12/09/2016</li>';
Choose either one of the above - both will work, although I find objects easier to work with.
From your comments,
hide the date if the date has passed
Note that when using the less than operator <, doing $date < $now will evaluate to true if the date is in the past, and hide the content if the date is in the future. If you desire the opposite behavior, you just use the greater than operator <.
Here's a live demo: https://3v4l.org/N74G2
References
http://php.net/datetime.construct
http://php.net/strtotime
http://php.net/language.operators.comparison
You need to parse your date from your format '09-19-2016' to a timestamp or DateTime object, which PHP will be able to compare as a date. You can use PHP's date_parse_from_format() to do so.
For example:
$date = '09-19-2017';
$parsed = date_parse_from_format('m-d-Y', $date);
$timestamp = mktime(
$parsed['hour'],
$parsed['minute'],
$parsed['second'],
$parsed['month'],
$parsed['day'],
$parsed['year']
);
if ($timestamp < time()) {
echo 'older';
} else {
echo 'newer';
}
This will give you the correct answer while keeping your current format. You can see an working example here: https://3v4l.org/NIoId
I want to check if 30 min passed after created time in database. created is a time column having time stamp in this format 1374766406
I have tried to check with date('m-d-y H:i, $created) but than of course it is giving human readable output so don't know how to perform check if current time is not reached to 30min of created time.
Something like if(created > 30){}
Try this:
$created = // get value of column by mysql and save it here.
if ($created >= strtotime("-30 minutes")) {
// its over 30 minutes old
}
The better approach is to use DateTime for (PHP 5 >= 5.3.0)
$datenow = new DateTime();
$datenow->getTimestamp();
$datedb = new DateTime();
$datedb->setTimestamp(1374766406);
$interval = $datenow->diff($datedb);
$minutes = $interval->format('%i');
$minutes will give you the difference in minutes, check here for more
http://in3.php.net/manual/en/datetime.diff.php
Here is the working code
http://phpfiddle.org/main/code/jxv-eyg
You need to use strtotime(); to convert the date in human form back to a timestamp, then you can compare.
EDIT: Maybe I misread.
So something like;
if(($epoch_from_db - time()) >= 1800){
//do something
}
i have following code i am trying to compare two get in order to get into if statement but i something wrong with is code.
the following code should run if the time is above 23:29 and less then 08:10...
$gettime="04:39"; // getting this from database
$startdate = strtotime("23:29");
$startdate1 = date("H:i", $startdate);
$enddate = strtotime("08:10");
$enddate1 = date("H:i", $enddate);
//this condition i need to run
if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1))
{
echo"ok working";
}
please help me in dis regard
thanks
Make sure your comaring the right types of data, time stamps with time stamps and not w/ strings etc...
$gettime= strtotime("22:00"); // getting this from database
$startdate = strtotime("21:00");
//$startdate1 = date("H:i", $startdate);
$enddate = strtotime("23:00");
//$enddate1 = date("H:i", $enddate);
//this condition i need to run
if($gettime >= $startdate && $gettime <= $enddate)
{
echo"ok working";
}
You are comparing the string with a date.
$gettime is a string and you are comparing it with a time object.
You need to convert $gettime to a time object by calling $gettime = strtotime($gettime), and then you can compare it using > or < like you have above.
Assuming you're receiving the time from the DB in a date format (and not as a string):
change:
if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1))
to:
if($gettime >= strtotime($startdate1) || $gettime <= strtotime($enddate1))
For comparing times, you should use the provided PHP classes
The DateTime::diff will return an object with time difference info:
http://www.php.net/manual/en/datetime.diff.php
You may refer to PHP documentation about DateTime::diff function at their website http://php.net/manual/en/datetime.diff.php
You may also go through this stackoverflow question How to calculate the difference between two dates using PHP?
I have a field in database that has type of datetime in which I add time when user visit a page. When user again comes I want to check the interval between his first visit and current. If it is less or equal to 1 hour then I want to show him some message.
I store time like this
2011-03-04 00:25:01
The thing that I want to ask that how to check the interval in PHP
You could try
SELECT COUNT(#UserID) FROM table WHERE LastVisit > (DateADD(now(),interval -1 Hour))
you can then check the count
Edit: added FROM clause
If you have PHP >= 5.3 you can use DateTime objects and functions:
$visit = DateTime::createFromFormat('Y-m-d H:i:s', '2011-03-04 00:25:01');
$now = new DateTime("now");
$diff = $now->diff($visit);
What you can so is, retrieve the the datetime, store it in a variable.
Create a var with time().
You can then convert the db datetime to a timestring using strtotime()
Subtract the datetime timestring from the new time. That should give you a difference in seconds. You can then manipulate your values and do the relevant checks.
$db = datetime_from_database;
$now = time();
$last = strtotime($db);
$diff = $now - $last; //this is in seconds
You can do something like
$minutes = $diff / 60;
If ($minutes > 60) echo 'more than 1 hour; 60 minutes';
Just work in it.
You can then use the date functions to format the new datetime using the $now and update the database.
In php i get the variable $date_time in this format -- 11-01-2010 20:48:25 . This time is GMT time. I have a 2 hour flexibility and if it exceeds 2 hours then i have to reject it. I am set in EST, but i want to do the check based on GMT only so that there is no errors in the time difference. How can i set to GMT in my php code and how do i check for the 2 hours flexible time difference? like for this example it is acceptable for any time between 11-01-2010 18:48:25 and 11-01-2010 22:48:25. Also will it be an issue if $date_time is 11-01-2010 23:48:23?
Clarification
I am doing a $date_time=$_GET['date_time'];. Then i need to check if this new $date_time if within 2 hours range of the current GMT time. if it is in the range, then i will proceed to execute that code, else i will show an error or do something else. I wanted to know how i am going to check this 2 hours range for this $date_time variable.
Here is a way how to convert your time format into a UNIX timestamp:
$date = strptime($date_time, "%m-%d-%Y %T");
$ut = mktime($date['tm_hour'], $date['tm_min'], $date['tm_sec'], 1 + $date['tm_mon'], $date['tm_mday'], 1900 + $date['tm_year']);
$now = time();
if($ut >= $now && $ut <= ($now + 7200)) { // 7200 = 2 * 60 * 60 seconds
// allowed
}
Reference: strptime, mktime, time.
Note: time() always returns the UNIX timestamp in UTC (regardless of time settings). So this assumes that the $date_time timestamp is a GMT time.
Working example (of course you have to provide a valid GMT time for $date_time).
Note 2: If the input time is not in GMT, you can set the timezone with date_default_timezone_set (affects mktime but not time).
Working example (change time and timezone accordingly)
If PHP >= 5.3 (you've got a seriously weird format BTW):
date_default_timezone_set('EST');
$inputtime = DateTime::createFromFormat('m-d-Y H:i:s','11-01-2010 20:48:25',new DateTimeZone("GMT"));
$diff = $inputtime->getTimestamp() - time();
if(abs($diff) > 7200){
//more then 2 hours difference.
}
If you run on PHP > 5.3, you can use DateTime for this :
$my_date = "11-01-2010 20:48:25";
$date = DateTime::createFromFormat('m-d-Y H:i:s', $my_date);
$date_lower = DateTime::createFromFormat('m-d-Y H:i:s', $my_date);
$date_upper = DateTime::createFromFormat('m-d-Y H:i:s', $my_date);
$date_lower->sub(new DateInterval('PT2H'));
$date_upper->add(new DateInterval('PT2H'));
var_dump($date >= $date_lower && $date <= $date_upper); // bool(true)
I find it more readable.
You can also use another timezone if necessary, check the third argument of createFromFormat.
I suggest you to never pass times and dates with format string. Just convert it later. You just pass the timestamp as a get variable and then you format it in the script.
It's the best solution and also the cleanest.
Then use the following code:
$flexibility = X seconds;
if ($date_time < time() - $flexibility or $date_time > time() + $flexibility)
{ /*Error*/ }