• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 255
  • Last Modified:

Comparing datetimes and timezone issue

I have the following code to retrieve a date and compare with the present time, which works, but what if I want to say as long as it's still today, count it as the future, even though the time might have past already.

Also, I'm not too sure how to handle time zones with this, as $commenceDate, which is stored in MySQL database  and refers to a GMT +8 timezone. I'm using PHP 4.3.

$commenceDateTime = $row['commenceDateTime']; //read from MySQL datetime field
$commenceDateTime = strtotime( $commenceDateTime );

$currentDateTime = mktime();

if ($currentDateTime >= $commenceDateTime) {
   echo "past";
}

else {
   echo "future";
}
0
skylabel
Asked:
skylabel
1 Solution
 
nizsmoDeveloperCommented:
To solve the timezone problem, when the $commenceDateTime is retrieved from the database, add 8 hours (or add/subtract however many you like to match your timezone) like this:

$commenceDateTime = $row['commenceDateTime'];
$commenceDateTime = strtotime("+8 hours", $commenceDateTime); // Adds 8 hours to the time from the database

As for your if it is today, count in the future we can write a little function like this which returns 0 if it is today:


function count_day($start_date, $end_date) {
   $start_date_unixtimestamp = strtotime($start_date);
   $start_date_day = date("d", $start_date_unixtimestamp);
   $end_date_unixtimestamp = strtotime($end_date);
   $end_date_day = date("d", $end_date_unixtimestamp);
   $calculated_date_unixtimestamp = $start_date_unixtimestamp;
   $counter=0;
   while ($calculated_date_unixtimestamp < $end_date_unixtimestamp)  
   {
       $counter++;
       $calculated_date_unixtimestamp = strtotime($start_date . " +{$counter} days");
   }
   #
   if ( ($counter==1) && ($end_date_day==$start_date_day)) $counter=($counter-1);
   return $counter;
}


Calling something like this:
count_day("2004-04-24", "2004-04-25");
Would return 1. And something like this:
count_day("2004-04-24", "2004-04-24");
would return 0.

Hope this helps.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now