PHP / CakePHP datetime compare

cakephp, php

Solution

This would be much easier with the DateTime functionality in PHP. I'm not exactly sure what you mean by "within 2 hours". I'm assuming you mean between 2 hours before and 2 hours after. If not you can change the intervals pretty easily.

$mysql_date_obj = new DateTime($date_from_mysql);
$before_time = new DateTime('now');
$before_time->add( DateInterval::createFromDateString('-2 hour') );
$after_time = new DateTime('now');
$after_time->add( DateInterval::createFromDateString('2 hour') );

if( $before_time <= $mysql_date_obj && $mysql_date_obj <= $after_time ) {
     // date is within 2 hours.
}

Documentation: http://php.net/DateTime

Problem

I am trying to check if a MySQL stored datetime object is within 2 hours of right now and just either show certain links or not based on if the ride_hour more than 2 hours in the future of the current hour. Here's what i've tried: ``` $now = date('Y-m-d'); $now_hour = date('h'); $ride_date = date('Y-m-d',strtotime($ride['Ride']['date'])); $full_ride_hour = date('h',strtotime($ride['Ride']['date'])); $ride_hour = $full_ride_hour-2; ``` So I'm comparing the day first to see if it is even happing today, if so i don't need to check the hour. otherwise, I'm trying to compare $ride_hour with $now_hour. The day is obviously working but the hour comparison does not seem to be working. The other thing I am trying to do, is in the cakePHP controller, is limit the results based on a sort value. I am trying to limit the results to either, ALL, Results with a date in the future, or results in the past, and paginate. Here's how I'm trying which isn't working: ``` switch ($sort) { case 0: $rides = $this->paginate('Ride',array('Ride.user_id' => $user_id,'Ride.date > now()')); break; case 1: $rides = $this->paginate('Ride',array('Ride.user_id' => $user_id)); break; case 2: $rides = $this->paginate('Ride',array('Ride.user_id' => $user_id,'Ride.date < now()')); break; } $this->set('sort',$sort); $this->set('rides', $rides); ``` Thank you!

Original source