2

I have a cron job that runs at midnight which resets all user limits for that day. I want to display something along the lines of Your limits reset in 1 hour 14 minutes to my users. Basically a countdown until midnight (server time).

At the moment I'm using this to find midnight:

strtotime('tomorrow 00:00:00');

which returns a timestamp for when midnight rolls over, but I have no idea how to display a user friendly countdown. Is there a PHP library for this or is this pretty easy without a library?

James Dawson
  • 5,309
  • 20
  • 72
  • 126
  • Yeah, that gets me the number of seconds left until midnight, but I don't know how to format that into something like `1 hour 14 minutes`. – James Dawson Jan 30 '13 at 21:23
  • 1
    For one, if you want an active countdown, you need to use javascript or something client side. PHP can give you the initial time (of server) but the client side code will have to handle the counting. check out: [SO Q](http://stackoverflow.com/questions/14563234/php-with-javascript-code-live-clock) – UnholyRanger Jan 30 '13 at 21:25
  • Having it update live isn't something that's needed, it just needs to give the user a rough idea. – James Dawson Jan 30 '13 at 21:28

3 Answers3

5

Simply this gives you left-minutes;

$x = time();
$y = strtotime('tomorrow 00:00:00');
$result = floor(($y - $x) / 60);

But you need to filter $result;

if ($result < 60) {
    printf("Your limits rest in %d minutes", $result % 60);
} else if ($result >= 60) {
    printf("Your limits rest in %d hours %d minutes", floor($result / 60), $result % 60);
}
Kerem
  • 11,377
  • 5
  • 59
  • 58
3

Since you're looking for a rough estimate, you could leave out the seconds.

$seconds = strtotime('tomorrow 00:00:00') - now();
$hours = $seconds % 3600;
$seconds = $seconds - $hours * 3600;
$minutes = $seconds % 60;
$seconds = $seconds - $minutes *60;

echo "Your limit will reset in $hours hours, $minutes minutes, $seconds seconds.";
UnholyRanger
  • 1,977
  • 14
  • 24
2

It is quite easy, just a little mathematics along with finding the difference in seconds between then and now.

// find the difference in seconds between then and now
$seconds = strtotime('tomorrow 00:00:00') - time(); 
$hours = floor($seconds / 60 / 60);   // calculate number of hours
$minutes = floor($seconds / 60) % 60; // and how many minutes is that?
echo "Your limits rest in $hours hours $minutes minutes";
Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108
  • I should've mentioned in my original post that I already tried this method and it doesn't seem accurate, the hour calculates as `1.5427777777778`, for example. – James Dawson Jan 30 '13 at 21:29
  • @JamesDawson And I should have remembered to use the `floor` function: http://www.php.net/manual/en/function.floor.php – Simon Forsberg Jan 30 '13 at 21:31