如何在 PHP 中显示一个月前

How to show month ago in PHP

$logintime value 1 year finished 意味着,它会显示 1 年前,但是假设 2 months only finished 意味着我想显示 2 个月前,但我的代码显示像 60 天前,我不知道在哪里我做错了,剩下的小时、分钟都可以正常工作,只有一个月有问题,$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'); 
    }
}

你的这行代码:

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

它说如果月份 > = 12,则显示几个月前,但你只有 2 个月。

所以您应该考虑将其更改为:

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