我在一个 PHP 网站上工作。我想在 7 天前一周后显示月份名称,如 - Jan、Feb、Dec 等。我正在使用一个函数以过去的格式显示日期时间。
public function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
它让我喜欢 - 5 seconds ago, 5 days ago, 5 weeks ago, and months, year ago
。但我想要——
5 seconds ago, 7 days ago then after 7 days should return like - 5 Jan
and if the year is not the current year then display like - 5 Jan 2022
我有一个专栏 created date datetime .
我怎样才能返回任何秒、任何天、任何一月、任何一月 2022?
我有一种方法可以通过 if 条件做到这一点。这对其他人会有帮助。创建一个条件,如 -
if($ago->diff($now)->days > 6)
{
return your desired date format like - 5 Jan or 5 Jan 2022
}
else
{
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
一周后,它将显示您想要的格式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句