将给定天数显示为“#Years,#Months,#Weeks,#Days”

时间:2013-01-25 18:11:20

标签: php sql datetime

使用SQL数据库中的“天数”,如何以更人性化的格式返回?

例如,对于许多用户来说,这个数字非常高。而不是他们看到“438天”,我想显示:“1年,2个月,1周,5天。”

谢谢!

2 个答案:

答案 0 :(得分:2)

Select floor(yourfield/365) + ' year(s), ' + 
       floor(mod(yourfield,365)/30) + ' month(s), ' + 
       floor(mod(mod(yourfield,365),30)/7) +' week(s), ' + 
       floor(mod(mod(mod(yourfield,365),30),7)) + ' day(s)'
FROM table

assumes + is valid operator in mySQL for string concat.
assumes 1 year = 365 days
assumes 1 month = 30 days
assumes 1 week = 7 days

鉴于我们不知道开始/结束日期,考虑到每月或闰年的日期是徒劳的。

答案 1 :(得分:-2)

您可以使用strtotime()DateTime

$time = strtotime("438 days ago");
$past = new DateTime(date('Y-m-d', $time));
$present = new DateTime(date('Y-m-d', time()));
$difference = $past->diff($present);
echo $difference->format('%a days %y years');

http://php.net/manual/en/function.date-diff.php