I am checking to see whether current time is inside a specified range but get odd behavior.
I wonder, maybe when I do $end_date->getTimestamp() I get the timestamp for the first minute of that day?
In that case I would need to add (60*60*24)-1 to the timestamp to get 23:59:59 of that $end_date right?
private function check_date_in_range($start_date, $end_date)
{
//Get current time
$user_ts = time();
if ($start_date == null && $end_date == null) {
//if both are null...
return 1;
}
elseif ($start_date != null && $end_date != null) {
// if none is null
//Convert dates to timestamp for comparison
$start_ts = $start_date->getTimestamp();
$end_ts = $end_date->getTimestamp();
// Check that current date is between start & end otherwise return FALSE.
return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
If you want to test for the inclusive range, you would indeed need to add one more day:
$now = new DateTime();
$end_date_next = $end_date;
$end_date_next->modify('+1 day');
return $now >= $start_date && $now < $end_date_next;
Or just use string based comparison on just the date portion instead:
$now = date('Y-m-d');
return $now >= $start_date->format('Y-m-d') &&
$now <= $end_date->format('Y-m-d');
You can do direct comparisons of DateTime objects, so something like this should work:-
/**
* @param DateTime $start_date
* @param DateTime $end_date
* @return bool
*/
private function check_date_in_range(\DateTime $start_date, \DateTime $end_date)
{
if ($start_date == null || $end_date == null) {
//if either is null bail.
return false;
}
$currDate = new \DateTime();
$start_date->setTime(0, 0, 0);
$end_date->setTime(23, 59, 59);
// Check that current date is between start & end otherwise return FALSE.
return ($start_date < $currDate && $currDate < $end_date);
}
You should realise too, that returning 1 can seem the same as returning true if you are using loose comparisons (==) in PHP.