您好,我正在尝试打印从mysql时间戳发布以来经过的时间

时间:2019-02-19 11:05:47

标签: php mysql

<?php
  date_default_timezone_set('Africa/Harare');

 function get_timeago($connect, $post_datetime){

    $query = "SELECT * FROM posts WHERE post_datetime = :post_datetime";
    $statement = $connect->prepare($query);
    $statement->execute(
        array(
            ':post_datetime' => $post_datetime
        )
    );
    $timeago = $post_datetime;
    $current_time = time();
    $time_difference = $current_time - $timeago; 
    $seconds = $time_difference;
    $minutes = round($seconds / 60);
    $hours   = round($seconds / 3600);
    $days    = round($seconds / 86400);
    $weeks   = round($seconds / 604800);
    $months  = round($seconds / 2629800); //((365 + 365 + 365 + 366)/4/12) * 24 * 3600
    $years   = round($seconds / 31557600); //$months * 12

    if($seconds <= 60){
        return 'Just Now';
    } else if($minutes <= 60){
        if($minutes == 1){
            return 'a minute ago';
        } else {
            return '$minutes minutes ago';
        }
    } else if($hours <= 60){
        if($hours == 1){
            return 'an hour ago';
        } else {
            return '$hours hrs ago';
        }
    } else if($days <= 7){
        if($days == 1){
            return 'Yesterday';
        } else {
            return '$days days ago';
        }
    } else if($weeks <= 4){
        if($weeks == 1){
            return 'a week ago';
        } else {
            return '$weeks weeks ago';
        }
    } else if($months <= 12){
        if($months == 1){
            return 'a month ago';
        } else {
            return '$months months ago';
        } 
    } else if($years == 1){
        return 'a year ago';
    } else {
        return '$years years ago';
    }
return $result;
}

<span class="description">Shared publicly <i class="fa fa-globe"></i> - '.get_timeago($connect, strtotime($row['post_datetime'])).'</span>

?>

它改为输出:

公开共享-$分钟分钟前

1 个答案:

答案 0 :(得分:1)

您的问题是这个

 '$years years ago'

反正它的一部分。在PHP中,单引号不会插入变量,它们不会被替换,而是被视为字符串文字。

请改为使用"双引号。

 $foo = 'replaced';
 echo "$foo"; //outputs replaced

 echo '$foo'; //outputs $foo