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



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

例如,对于许多用户来说,这个数字相当高。他们看到的不是"438天",而是显示:"1年2个月1周5天"。

谢谢!

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

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

您可以使用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

最新更新