簡體   English   中英

如何在網站上的相對時間內獲取MySQL表的時間戳

[英]How to get timestamp of MySQL table in relative time on website

我想逐步了解將mysql表中時間戳轉換為我網站上的相對時間( 4秒前,5個月前 ...)的方法。

有關信息,我的時間戳列名為creation ,而表名為users

我試過的代碼:

function relativedate($secs) {
    $second = 1;
    $minute = 60;
    $hour = 60*60;
    $day = 60*60*24;
    $week = 60*60*24*7;
    $month = 60*60*24*7*30;
    $year = 60*60*24*7*30*365;

    if ($secs <= 0) { $output = "now";
    }elseif ($secs > $second && $secs < $minute) { $output = round($secs/$second)." second";
    }elseif ($secs >= $minute && $secs < $hour) { $output = round($secs/$minute)." minute";
    }elseif ($secs >= $hour && $secs < $day) { $output = round($secs/$hour)." hour";
    }elseif ($secs >= $day && $secs < $week) { $output = round($secs/$day)." day";
    }elseif ($secs >= $week && $secs < $month) { $output = round($secs/$week)." week";
    }elseif ($secs >= $month && $secs < $year) { $output = round($secs/$month)." month";
    }elseif ($secs >= $year && $secs < $year*10) { $output = round($secs/$year)." year";
    }else{ $output = " more than a decade ago"; }

    if ($output <> "now"){
        $output = (substr($output,0,2)<>"1 ") ? $output."s" : $output;
    }
    return $output;
}



echo relativedate(60); // 1 minute

使用CASE顯示相對時間/日期。 我在此代碼中創建了表“示例”。

SELECT *, CASE
WHEN creation between date_sub(now(), INTERVAL 60 minute) and now() THEN concat(minute(TIMEDIFF(now(), creation)), ' minutes ago')
WHEN datediff(now(), creation) = 1 THEN 'Yesterday'
WHEN creation between date_sub(now(), INTERVAL 24 hour) and now() THEN concat(hour(TIMEDIFF(NOW(), creation)), ' hours ago')
ELSE date_format(creation, '%a, %m/%d/%y')
END as date FROM sample 

這將創建一個新列“日期”,可用於輸出相對時間。

我喜歡Jm Verastigue,並對其進行了一些微調,以增強當年內日期與當年外日期之間的增強,並且僅在utc_time上起作用,但是now()方法也是有效的。

SELECT 
report_time,
convert(CASE
    WHEN
        report_time between date_sub(utc_timestamp(),
            INTERVAL 60 minute) and utc_timestamp()
    THEN
        concat(minute(TIMEDIFF(utc_timestamp(), report_time)),
                ' minutes ago')
    WHEN datediff(utc_timestamp(), report_time) = 1 THEN 'Yesterday'
    WHEN
        report_time between date_sub(utc_timestamp(), INTERVAL 24 hour) and utc_timestamp()
    THEN
        concat(hour(TIMEDIFF(utc_timestamp(), report_time)),
                ' hours ago')
    WHEN
        year(report_time) >= year(utc_timestamp())
    THEN
        date_format(report_time, '%e %b')
    ELSE date_format(report_time, '%Y-%m-%d')
END using utf8) as `LekkerDate`

FROM
        _smry_prodinfo
    group by `LekkerDate`;

您可以通過PHP進行請求(稱為“ time ago”)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM