Days left to specifc date in php / WordPress

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 :

Read More
<?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!

Related posts

Leave a Reply

3 comments

  1. 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)

  2. 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 leftn";
    

    This takes into account DST and leap years.

  3. 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';