Vincent
Vincent

Reputation: 345

php - Time remaining until specific time from current time of page load

I have to admit that having not even tried to code this myself this question may be a annoying to some but I'm very surprised that I wasn't able to find a good example on the web of what I'm trying to do. Perhaps I'm just not using the right key words in my searches.

I am trying to calculate the time remaining from now (the time the page loads) until a specific date and time (let's say Wednesday May 11, 2011 12:00PM for example) and display it. I had thought it would be quite easy to find a snippet to accomplish this but no luck so far. Does anyone have some example code they have used to accomplish this before? I don't expect anyone to write this for me from scratch but if I can at least get pointed in the right direction it would be extremely helpful.

Upvotes: 18

Views: 42067

Answers (3)

Jimmy Sawczuk
Jimmy Sawczuk

Reputation: 13614

I'd use the DateInterval and DateTime functions:

$now = new DateTime();
$future_date = new DateTime('2011-05-11 12:00:00');

$interval = $future_date->diff($now);

echo $interval->format("%a days, %h hours, %i minutes, %s seconds");

You'll need a version of PHP that's at least 5.3 to do it this way - otherwise, do what helloandre recommends.

Upvotes: 62

Mahendra Jella
Mahendra Jella

Reputation: 5596

I think it will usefull

$startdate="2008-06-22 20:38:25"; 
$enddate="2008-06-29 21:38:49"; 

$diff=strtotime($enddate)-strtotime($startdate); 
echo "diff in seconds: $diff<br/>\n<br/>\n"; 

// immediately convert to days 
$temp=$diff/86400; // 60 sec/min*60 min/hr*24 hr/day=86400 sec/day 

// days 
$days=floor($temp); echo "days: $days<br/>\n"; $temp=24*($temp-$days); 
// hours 
$hours=floor($temp); echo "hours: $hours<br/>\n"; $temp=60*($temp-$hours); 
// minutes 
$minutes=floor($temp); echo "minutes: $minutes<br/>\n"; $temp=60*($temp-$minutes); 
// seconds 
$seconds=floor($temp); echo "seconds: $seconds<br/>\n<br/>\n"; 

echo "Result: {$days}d {$hours}h {$minutes}m {$seconds}s<br/>\n"; 
echo "Expected: 7d 0h 0m 0s<br/>\n"; 


echo "time isss".time();

echo   $date = date('Y-m-d H:i:s')";

?>

Upvotes: 5

helloandre
helloandre

Reputation: 10721

first you'll need to calculate the difference in seconds using time() and strtotime(). Then you can translate those seconds into days/hours/minutes/seconds.

Upvotes: 2

Related Questions