Comparing post date get_the_date() from today – WordPress

I want to be able to calculate the days that post was created and compare with today to echo “Today/ Yesterday/ Last Week/ Last Month”. The date format I get from get_the_date() is “December 1, 2015” so I’m wondering if I need to use a different function that I don’t know about.

Related posts

2 comments

  1. You just need to the get_the_date() function;

    Now Date Should In YYYY-MM-DD Format

    for that

    $date1 = date('Y-m-d', strtotime(get_the_date())) ;
    $current_date1 = date('Y-m-d', time()) ;
    

    Now use this function

    function dateDifference($date_1 , $date_2 )
    {
        $datetime1 = date_create($date_1);
        $datetime2 = date_create($date_2);
    
        $interval = date_diff($datetime1, $datetime2);
    
        return $interval->format('%a');
    
    }
    
    //call above function
    echo $days = dateDifference($date1, $current_date1);
    
  2. I’m not sure if there is any WordPress function but you can get your values using built in PHP functions.

    Yesterday:

    date('Y-m-d', strtotime("-1 day"));
    

    Last week

    date('Y-m-d', strtotime("-1 week +1 day"));
    

    Last month

    date('Y-m-'.1, strtotime("-1 month")); //First day of -1 month
    

    You can read more about strtotime here http://php.net/manual/en/function.strtotime.php

    Here is also a link to the date function, if you havent had any experience with it before: http://php.net/manual/en/function.date.php

    You would want to use Y-m-d format for wordpress querys read more about that here: http://php.net/manual/en/function.date.php

Comments are closed.