我有一个显示最新活动的小函数,它从db中获取unix格式的时间戳,然后用这一行回显:
date("G:i:s j M -Y", $last_access)
Run Code Online (Sandbox Code Playgroud)
现在我想将日期(j M -Y)替换为昨天,而今天如果最新活动在今天,则昨天也是如此.
我怎样才能做到这一点?
Ham*_*eed 38
我会找到最后一个午夜的时间戳和它之前$last_access
的时间戳,如果在两个时间戳之间,然后显示昨天,任何大于去年午夜的时间戳都将是今天 ......
我相信这比做日期算术更快.
实际上,我刚刚测试了这段代码,它看起来效果很好:
<?php
if ($last_access >= strtotime("today"))
echo "Today";
else if ($last_access >= strtotime("yesterday"))
echo "Yesterday";
?>
Run Code Online (Sandbox Code Playgroud)
Key*_*eyo 15
function get_day_name($timestamp) {
$date = date('d/m/Y', $timestamp);
if($date == date('d/m/Y')) {
$date = 'Today';
}
else if($date == date('d/m/Y',now() - (24 * 60 * 60))) {
$date = 'Yesterday';
}
return $date;
}
print date('G:i:s', $last_access).' '.get_day_name($last_access);
Run Code Online (Sandbox Code Playgroud)
你必须每天比较,secondes comparaison是完全错误的:
如果我们今天早上,这意味着昨天晚上是今天(减去24小时)^^
这是我用于Kinoulink(一家法国创业公司)的方法:
public function formatDateAgo($value)
{
$time = strtotime($value);
$d = new \DateTime($value);
$weekDays = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche'];
$months = ['Janvier', 'Février', 'Mars', 'Avril',' Mai', 'Juin', 'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'Décembre'];
if ($time > strtotime('-2 minutes'))
{
return 'Il y a quelques secondes';
}
elseif ($time > strtotime('-30 minutes'))
{
return 'Il y a ' . floor((strtotime('now') - $time)/60) . ' min';
}
elseif ($time > strtotime('today'))
{
return $d->format('G:i');
}
elseif ($time > strtotime('yesterday'))
{
return 'Hier, ' . $d->format('G:i');
}
elseif ($time > strtotime('this week'))
{
return $weekDays[$d->format('N') - 1] . ', ' . $d->format('G:i');
}
else
{
return $d->format('j') . ' ' . $months[$d->format('n') - 1] . ', ' . $d->format('G:i');
}
}
Run Code Online (Sandbox Code Playgroud)