How to get the number of hours untill midnight with PHP

蹲街弑〆低调 提交于 2019-12-05 14:50:16

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.

Maybe something like this? I have to admit to not completely understanding what your desired output is:

$d1 = new DateTime('2012-08-22 20:11:20');                                                                                          
$d2 = new DateTime('2012-08-23 00:00:00');

$interval = $d1->diff($d2);

echo $interval->format('%h hours %i minutes and %s seconds');

Nice and easy:

$timeLeft = 86400 - (time() - strtotime("today"));
echo date("H:i:s", $timeLeft);

86400 is the initial time of a day.
time() is the current time.
strtotime("today") is the starttime of this day.

date("H:i:s", $timeLeft) is for the formatting in hours, minutes and seconds.

Even shorter way:

date("H:i:s", strtotime("tomorrow") - time())

midnight is not more than the next day without specifying time the best way to do it must be :

<?php
$datetime1 = new DateTime(date('Y-m-d H:i:s'));//current datetime object
$datetime2 = new DateTime(date('Y-m-').date(d));//next day at midnight
$interval = $datetime1->diff($datetime2);//diference
echo $interval->format('H');printing only hours (same as date format)
?>

if you want to know more : php date_diff

You can try this:

$now = strtotime('2012-08-22 20:11:20');
$midnight = strtotime('2012-08-23 00:00:00');
$difference = $midnight - $now;

echo date("H:i:s", $difference);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!