I am trying to build a count-down widget.
Given a certain date, whats the easiest way in PHP to determine how many days until that date?
I am trying to build a count-down widget.
Given a certain date, whats the easiest way in PHP to determine how many days until that date?
<?php
$cdate = mktime(0, 0, 0, 12, 31, 2009);
$today = time();
$difference = $cdate - $today;
if ($difference < 0) { $difference = 0; }
echo floor($difference/60/60/24)." days remaining";
?>
Expanding on schnaader's answer, here is a one-liner function that takes a date string as a parameter but only returns the number of days:
<?php
function days_until($date){
return (isset($date)) ? floor((strtotime($date) - time())/60/60/24) : FALSE;
}
?>
Don't treat dates as integers. Use your database, which has good support for dealing with calendars/time.
select datediff("2009-11-12", now())
PHP 5.3 has introduced the DateTime class that implements a 'diff' function. See http://www.php.net/manual/en/datetime.diff.php
Days minutes and seconds format:
// current time
$today = new DateTime(format_date(time(), 'custom', 'd M Y H:i:s'));
// date to which we want to compare (A Drupal field in my case).
$appt = new DateTime(format_date($yourdate_is_timestamp, 'custom', 'd M Y H:i:s' ));
// Months
$months_until_appt = $appt->diff($today)-> m;
// days
$days_until_appt = $appt->diff($today)-> days;
// hours
$hours_until_appt = $appt->diff($today)-> h;
// minutes
$minutes_until_appt = $appt->diff($today)-> i;
// seconds
$seconds_until_appt = $appt->diff($today)-> s;
echo 'days until: ' . $days_until_appt;
echo 'hours until: ' . $hours_until_appt;
echo 'minutes until: ' . $minutes_until_appt;
echo 'seconds until: ' . $seconds_until_appt;
I have just come across this in my code for a live app where the system incorrectly regarded today and tomorrow as today. We have just gone into British Summer Time and this has caused a problem with our app.
I am now using the following, which is giving me the correct result:
function days_away_to($dt) {
$mkt_diff = strtotime($dt) - time();
return floor( $mkt_diff/60/60/24 ) + 1; # 0 = today, -1 = yesterday, 1 = tomorrow
}
Of course, using the DateTime class is the best solution going forward ...