Reputation: 1280
I'm trying to get a simple "XX days left" for a custom post time I'm working with (jobs). I've tried to find the answer everywhere but nothing adapts well, changed my code 1000 times following examples on internet but I couldn't solve.
My code looks like this :
<?php
$today = date('d/m/Y');
$today = strtotime($today);
$finish = get_field('todate');
$finish = strtotime($finish);
//diference
$diff = $finish - $today;
$daysleft=floor($diff/(60*60*24));
echo "$daysleft days left";
?>
on $finish the get_field ('todate') returns the date dd/mm/yyyy
Anyone who can help me please?
Thanks!
Upvotes: 2
Views: 5206
Reputation: 813
How about this function?
function DayDifference($start, $end) {
$start = strtotime($start);
$end = strtotime($end);
$difference = $end - $start;
return round($difference / 86400);
}
echo DayDifference("2012-02-10", "2012-02-20").' days left';
Upvotes: 0
Reputation: 69957
strtotime
will only parse a date in day-month-year format if the values are separated by dots, tabs, or dashes. See Date Formats.
If you have PHP 5.2 or greater, you can use the following function to get total days:
<?php
$today = date('m/d/Y');
$today = new DateTime($today);
$finish = get_field('todate'); // MAKE SURE THIS IS m/d/Y or Y/m/d
$finish = new DateTime($finish);
//diference
$diff = $finish->diff($today);
$daysleft = $diff->format('%a'); // %a modifier means total days
echo "$daysleft days left\n";
This takes into account DST and leap years.
Upvotes: 1
Reputation: 26160
The issue is the arrangement of the d/m/Y (it should be m/d/Y) in your $today and $finish variables (for a listing of valid date formats that work with strtotime, visit the PHP Date Format page):
<?php
$today = date('m/d/Y');
$today = strtotime($today);
$finish = get_field('todate');
$finish = strtotime($finish);
//difference
$diff = $finish - $today;
$daysleft=floor($diff/(60*60*24));
echo "$daysleft days left";
?>
Tested and works, assuming the $finish date is entered as m/d/yyyy (not as d/m/yyyy)
Upvotes: 4