How to Calculate Seconds Until the End of the Day in PHP

How to Calculate Seconds Until the End of the Day in PHP

Since there is no such built-in function in PHP, I had to write my own implementation:

function get_seconds_to_midnight()
{
	$left_day_hh = 23 - intval(date('H'));
	$left_day_mm = 59 - intval(date('i'));
	$left_day_ss = 60 - intval(date('s'));
	
	return 3600 * $left_day_hh + 60 * $left_day_mm + $left_day_ss;
}

For testing, we use the following code:

echo 'SECONDS: '.get_seconds_to_midnight().'<hr>';
echo 'NOW: '.date('d.m.Y H:i:s').'<hr>';
echo 'MIDNIGHT: '.date('d.m.Y H:i:s', time() + get_seconds_to_midnight()).'<hr>';

In short, we subtract the current time from the end-of-day time and get the difference in seconds by converting hours and minutes and adding seconds.

Posts on similar topics

Are you having problems with your WordPress site? Do you need additional functionality? A custom plugin or a new page?
Then write to me via the feedback form, and I will try to help you.

Write a comment

Your email address will not be published. Required fields are marked *