How to get the number of hours untill midnight with PHP

Michael Ecklund picture Michael Ecklund · Aug 23, 2012 · Viewed 7.8k times · Source

Scenario: An record was entered into the database.

I am trying to figure out the following equations:

  1. How to get the number of hours since the record was added.
  2. How to get how many hours are left until midnight since the record was added.

Given these times:

  • Date / Time: 2012-08-22 20:11:20
  • Time Stamp: 1345684280
  • Midnight Tonight: 2012-08-23 00:00:00
  • Midnight Time Stamp: 1345698000

I feel like I'm on the right track. Just need some proper math to do the calculations? I am horrible at math. Any help or guidance would be appreciated. I'm not looking for someone to COMPLETE THIS FOR ME. Just looking for advice on what I'm doing wrong, or how I could do it better. Maybe explain the math formulas necessary to achieve my goal.

Here is what I have so far:

class tools{

    public function __construct(){
    }

    public function check_time($time, $request){
        $time = strtotime($time);
        if($request == 'since'){
            $theTime = time() - $time;
            $prefix = 'Since:';
        } elseif($request == 'until'){
            $midnight = mktime(0, 0, 0, date('n'), date('j'), date('Y'));
            $theTime = $midnight - $time;
            $prefix = 'Until:'; 
        }

        $tokens = array (
            31536000 => 'year',
            2592000 => 'month',
            604800 => 'week',
            86400 => 'day',
            3600 => 'hour',
            60 => 'minute',
            1 => 'second'
        );

        foreach($tokens as $unit => $text){
            if($theTime < $unit) continue;
            $duration = floor($theTime / $unit);
            return $prefix.' '.$duration.' '.$text.(($duration>1)?'s':'');
        }
    }
}// EoF tools class

$tools = new tools();

print_r($tools->check_time('2012-08-22 20:11:20', 'since'));
print_r($tools->check_time('2012-08-22 20:11:20', 'until'));

Answer

kcarter609 picture kcarter609 · Aug 24, 2012

The solution here is very simple. There is a minor error that's causing all of your issues.

In your code you have this to calculate midnight.

$midnight = mktime(0, 0, 0, date('n'), date('j'), date('Y'));

This is incorrect for the simple fact that it's using TODAY's midnight (Which would have been 00:00 today, however many hours ago from now. You want midnight TOMORROW, since it's considered 00:00 on 24 hour time and is tomorrow. The correct way to do it is just like this:

$midnight = strtotime("tomorrow 00:00:00");

Just keep in mind that strtotime() bases everything off of GMT, so make sure you set a default timezone in the file/application.

I hope my answer is clear and explains why the code you posted is wrong and how to fix it.