Search code examples
phpphp-5.4

How to show month ago in PHP


$logintime value 1 year finished means, it will showing 1 years ago, but suppose 2 months only finished means I want to show 2 months ago, but my code showing like 60 days ago, I don't know where I did mistake, remaining hour, minutes this are working fine, only month making problem, $logintime = 2016-02-27 03:00:00

function timeAgo($logintime) {
    date_default_timezone_set('UTC');
    date_default_timezone_set('Asia/Kolkata');
    $start_date = new DateTime($logintime);
    $since_start = $start_date->diff(new DateTime(date("Y-m-d h:i:s")));

    if (intval($since_start->format('%Y') ) >= 1) {
        echo $year = $since_start->format('%Y years ago');
    } else if (intval($since_start->format('%m')) >= 12) {
        echo $months = $since_start->format('%m month ago');
    } else if (intval($since_start->format('%a')) >= 1) {
        echo $days = $since_start->format('%a days ago');
    } else if (intval($since_start->format('%h')) >= 1) {
        echo $hourss = $since_start->format('%h hours ago');    
    } else if (intval($since_start->format('%i')) >= 1) {
        echo $min = $since_start->format('%i minuts ago');  
    } else if (intval($since_start->format('%s')) >= 1) {
        echo $min = $since_start->format('%s seconds ago'); 
    }
}

Solution

  • Your this line of code :

    else if(intval($since_start->format('%m')) >= 12){
    

    It says if the month > = 12, then show months ago, but you just have 2 months.

    So you should consider changing it to :

    else if(intval($since_start->format('%m')) >= 1){