php - 如何将时间前功能限制在 12 个月以下并发布一年或更晚的实际日期?
问题描述
我想发布一篇文章的实际日期(即 2015 年 4 月 5 日),如果它自发布以来已经一年或更长时间。如果不到一年,我想使用时间前功能(即 6 个月前)。
我尝试在 HumanTiming Time Ago Function 中注释掉年份(由 arnorhs 发布)并向其添加 if/else 条件
$time = strtotime('2015-04-05 17:25:43');
echo 'event happened '.humanTiming($time).' ago';
function humanTiming ($time)
{
$time = time() - $time; // to get the time since that moment
$time = ($time<1)? 1 : $time;
$tokens = array (
//31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
if($time > $tokens){
echo "April 5, 2015";
} else {
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
}
我希望输出为“2015 年 4 月 5 日”,但它忽略了 if/else 条件并将日期发布为“36 个月前”。
我怎样才能达到我想要的结果?
解决方案
使用 DateTime 更简单
$now = new DateTime();
$then = new DateTime('April 5, 2015');
$diff = $now->diff($then); // returns DateInterval object or false on failure
if ($diff->y >= 1) {
// show your date
echo $then->format('Y-m-d H:i:s');
} else {
// show the interval
echo $diff->format('%d days ago');
}
查看文档以获取更多信息
推荐阅读
- mysql - 如何在 MariaDB 中使用 LIKE 运算符获取最大和最小 4 个字符的 PostalCode 列表?
- python - 如何从字母和数字中找到所有可能的组合
- jquery - JQuery里面的js函数
- sql-server - 查询时态表
- twilio - SMS 消息未发送到 Etisalat 阿拉伯联合酋长国号码
- python - 从脚本运行 Scrapy 时访问我的蜘蛛产生的项目
- batch-file - cmd 不将结果输出到文件
- java - 如何在Java中获取exe的相对路径
- hugo - 如何在 Hugo 中打印出变量的完整值
- javascript - 如何让浏览器扩展弹出窗口显示变量