[ACCEPTED]-How many days until X-Y-Z date?-datetime
<?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";
?>
0
Expanding on schnaader's answer, here is 3 a one-liner function that takes a date string 2 as a parameter but only returns the number 1 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 2 database, which has good support for dealing 1 with calendars/time.
select datediff("2009-11-12", now())
PHP 5.3 has introduced the DateTime class 1 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;
0
I have just come across this in my code 6 for a live app where the system incorrectly 5 regarded today and tomorrow as today. We 4 have just gone into British Summer Time 3 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 2 course, using the DateTime class is the 1 best solution going forward ...
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.