Calculate time left in day in PHP

Josh Sherman
2 min read
Software Development PHP

Before PHP 5.3, finding the difference between two dates was a bit of a pain. Convert the date strings to UNIX timestamps (if they weren’t already), subtract them, and then divide the result until you had each of the components (seconds, minutes, et cetera). As of PHP 5.3+ you can leverage the DateTimeInterface:

<?php
$today      = new DateTime('now');
$tomorrow   = new DateTime('tomorrow');
$difference = $today->diff($tomorrow);

echo $difference->format('%h hours %i minutes %s seconds until tomorrow');

Not much to it, but it could be better as it would display zero values like “0 hours” or plurals when it should be singular, like “1 minutes”. To do that, we would want to grab the individual values, check if we should even display the value and then pluralize it:

<?php
$h = $difference->format('%h');
$m = $difference->format('%i');
$s = $difference->format('%s');

if ($h) {
  echo sprintf(ngettext('%d hour', '%d hours', $h), $h) . ' ';
}

if ($m) {
  echo sprintf(ngettext('%d minute', '%d minutes', $m), $m) . ' ';
}

if ($s) {
  echo sprintf(ngettext('%d second', '%d seconds', $s), $s) . ' ';
}

echo 'until tomorrow';

And since I’m feeling frisky, let’s try this again with even less code:

<?php
$values = array(
  'hour'   => $difference->format('%h'),
  'minute' => $difference->format('%i'),
  'second' => $difference->format('%s'),
);

foreach ($values as $word => $val) {
  if ($val) {
    echo sprintf(ngettext('%d ' . $word, '%d ' . $word . 's', $val), $val) . ' ';
  }
}

echo 'until tomorrow';

p.s. If you’re not using PHP 5.3+ you really should be looking for a tutorial on how to upgrade, not this post ;)

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Engineering Manager and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles