我想在帖子中创建年龄。结果必须像这样: 刚刚, 1 分钟前, 1 小时前, 1 天前, 1 几个月前后& 1 多年前。
$datetime1 = date_create($value['date']);
$datetime2 = date_create("now");
$diff=date_diff($datetime1,$datetime2);
if($diff->i >0){
$final_date = $diff->format("%I Minutes Ago");
}else if($diff->h >0){
$final_date = $diff->format("%H Hours Ago");
}else if($diff->y >0){
$final_date = $diff->format("%Y Years Ago");
}else if($diff->m >0){
$final_date = $diff->format("%M Months Ago");
}else if($diff->d >0){
$final_date = $diff->format("%D Days Ago");
} else {
$final_date = "Just Now";
}
我$value['date']
的约会就像这样 2018-05-11 07:38:47 。
当我使用该代码运行时,结果仅显示在分钟中,不会工作数小时,白天等...
答案 0 :(得分:0)
为了帮助你,我已经开始使用上面提到的方法构建了一个工作示例:
// DATE
$value['date'] = "2018-05-11 07:38:47";
// HTML VARIABLE
$final_date = '';
// DATE OBJECTS
$datetime1 = date_create($value['date']);
$datetime2 = date_create("now");
// DATE OBJECTS DIFFERENCE
$diff = date_diff($datetime1, $datetime2);
// IF DIFFERENCE IS LESS THAN ONE MINUTE, DISPLAY "Just Now"
if($diff->i == 0)
{
$final_date = $diff->format("Just Now");
}
else
{
// ELSE, CONCATENATE STRING FOR EACH VALID DIFFERENCE
if($diff->i > 0)
{
$final_date = $diff->format("%I Minutes Ago, ");
}
if($diff->h > 0)
{
$final_date .= $diff->format("%H Hours Ago, ");
}
if($diff->y > 0)
{
$final_date .= $diff->format("%Y Years Ago, ");
}
if($diff->m > 0)
{
$final_date .= $diff->format("%M Months Ago, ");
}
if($diff->d > 0)
{
$final_date .= $diff->format("%D Days Ago, ");
}
// REMOVE THE FINAL ", " FROM THE STRING
$final_date = substr($final_date, 0, -2);
}
// DISPLAY RESULT
echo $final_date;
答案 1 :(得分:0)
$datetime1 = date_create($value['date']);
$datetime2 = date_create("now");
$diff = date_diff($datetime1, $datetime2);
if ($diff->i > 0) {
echo $min = $diff->format("%I Minutes Ago")."<br/>";
} if ($diff->h > 0) {
echo $hr = $diff->format("%H Hours Ago")."<br/>";
} if ($diff->y > 0) {
echo $yr = $diff->format("%Y Years Ago")."<br/>";
} if ($diff->m > 0) {
echo $mn = $diff->format("%M Months Ago")."<br/>";
} if ($diff->d > 0) {
echo $day = $diff->format("%D Days Ago")."<br/>";
} else {
echo $just = "Just Now"."<br/>";
}