15

In PHP, how can I get the number of seconds until the end of day?

Thanks.

Psyche
  • 8,513
  • 20
  • 70
  • 85

5 Answers5

42

First thought:

86400 - date('H') * 3600 - date('i') * 60 - date('s')

Faster version derived from VolkerK's answer:

strtotime('tomorrow') - time()
chaos
  • 122,029
  • 33
  • 303
  • 309
  • 1
    Second method is technically better as well as being faster. Not all days have 86400 seconds. See: http://stackoverflow.com/questions/7780464/is-time-guaranteed-to-be-leap-second-aware – Joel Mellon Jan 29 '14 at 21:52
  • ...and a more practical reason why 86400 isn't quite good enough: http://stackoverflow.com/questions/2411564/march-14th-not-86400-seconds-long – Joel Mellon Jan 29 '14 at 21:56
8
$rs = strtotime('24:00') - time();
echo $rs;

edit: even faster

echo mktime(24,0,0) - time();
VolkerK
  • 95,432
  • 20
  • 163
  • 226
7

If you're using Carbon you can simply use

Carbon::now()->secondsUntilEndOfDay();

acolve
  • 109
  • 1
  • 3
1

Here you go! You can specify the timezone too:

    $timezone = new DateTimeZone( 'Asia/Kolkata' );

    $today = new DateTime('now', $timezone);
    $tomorrow = new DateTime('tomorrow', $timezone);
    $secondsLeftInTheDay = $tomorrow->getTimestamp() - $today->getTimestamp();

    echo $secondsLeftInTheDay;
Chirag
  • 149
  • 2
  • 17
0
$sDate = '2014-12-01 23:59:58';
$oDatetime1 = new DateTime($sDate);
$oDatetime2 = new DateTime($sDate);

$oDatetime1->modify( 'tomorrow' );

echo $oDatetime1->getTimestamp() - $oDatetime2->getTimestamp();
FDisk
  • 8,493
  • 2
  • 47
  • 52