Link to home
Start Free TrialLog in
Avatar of bschwarting
bschwarting

asked on

subtract current time to end of day - php

How do I subtract the current time till the end of the day in PHP?

2:33:27 - 12:00:00 (midnight)

I want a result of 9 hours 27 minutes and 33 seconds
Avatar of Beverley Portlock
Beverley Portlock
Flag of United Kingdom of Great Britain and Northern Ireland image

This will do it as spec'd

<?php

$now = date("Y-m-d");
$tomorrow = strtotime("$now +1 day");
$timeLeft = $tomorrow - time();

echo date("H \h\o\u\\r\s i \m\i\\n\u\\t\e\s s \s\e\c\o\\n\d\s",$timeLeft);
?>

The escaping is to stop the date function interpreting the text as directives.
If you want to split out the hours etc then alter the above like so

<?php

$now = date("Y-m-d");
$tomorrow = strtotime("$now +1 day");
$timeLeft = $tomorrow - time();

$hours = date("H",$timeLeft);
$mins  = date("i",$timeLeft);
$secs  = date("s",$timeLeft);

echo "Time left is $hours hours, $mins minutes and $secs seconds";
?>
Avatar of bschwarting
bschwarting

ASKER

the 1st option gives me 4 hours instead of 9.
Well, it would do - there is only 4 hours (or so) to midnight - in this timezone.....
ASKER CERTIFIED SOLUTION
Avatar of Roger Baklund
Roger Baklund
Flag of Norway image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
perfect, thanks!
OK here it is modified to use your example time (which gives 9 hours to go)

<?php
$sampleTime = strtotime("14:33:27");

$now = date("Y-m-d");
$tomorrow = strtotime("$now +1 day");
$timeLeft = $tomorrow - $sampleTime;

$hours = date("H",$timeLeft);
$mins  = date("i",$timeLeft);
$secs  = date("s",$timeLeft);

echo "Time left is $hours hours, $mins minutes and $secs seconds";
?>