我正在尝试转换格式为2009-09-12 20:57:19的时间戳,并将其转换为3分钟前用PHP。
我找到了一个有用的脚本来做这件事,但我认为它正在寻找一种不同的格式来用作时间变量。我想修改的脚本与此格式的工作是:
function _ago($tm,$rcs = 0) {
$cur_tm = time();
$dif = $cur_tm-$tm;
$pds = array('second','minute','hour','day','week','month','year','decade');
$lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
$no = floor($no);
if($no <> 1)
$pds[$v] .='s';
$x = sprintf("%d %s ",$no,$pds[$v]);
if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0))
$x .= time_ago($_tm);
return $x;
}
我认为在前几行脚本试图做的事情看起来像这样(不同的日期格式数学):
$dif = 1252809479 - 2009-09-12 20:57:19;
如何将我的时间戳转换成那种(unix?)格式?
我想有一个荷兰版本,支持单复数。仅仅在结尾加一个“s”是不够的,我们用的是完全不同的词,所以我重写了这篇文章的顶部答案。
这将导致:
2年1个月2周1天1分2秒
or
1年2个月1周2天1分1秒
public function getTimeAgo($full = false){
$now = new \DateTime;
$ago = new \DateTime($this->datetime());
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'jaren',
'm' => 'maanden',
'w' => 'weken',
'd' => 'dagen',
'h' => 'uren',
'i' => 'minuten',
's' => 'seconden',
);
$singleString = array(
'y' => 'jaar',
'm' => 'maand',
'w' => 'week',
'd' => 'dag',
'h' => 'uur',
'i' => 'minuut',
's' => 'seconde',
);
// M.O. 2022-02-11 I rewrote this function to support dutch singles and plurals. Added some docs for next programmer to break his brain :)
// For each possible notation, if corresponding value of current key is true (>1) otherwise remove its key/value from array
// If the value from current key is 1, use value from $singleString array. Otherwise use value from $string array
foreach ($string as $k => &$v) {
if ($diff->$k) {
if($diff->$k == 1){
$v = $diff->$k . ' ' . $singleString[$k];
} else {
$v = $diff->$k . ' ' . $v;
}
} else {
if($diff->$k == 1){
unset($singleString[$k]);
} else {
unset($string[$k]);
}
}
}
// If $full = true, print all values.
// Values have already been filtered with foreach removing keys that contain a 0 as value
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . '' : 'zojuist';
}
你应该先测试一下,因为我不是一个优秀的程序员:)