$startdate = new DateTime("2013-11-15");
$enddate = new DateTime("2013-11-20");
$timestamp_start = strtotime($startdate);
$timestamp_end = strtotime($enddate);
$difference = abs($timestamp_end - $timestamp_start);
$days = floor($difference/(60*60*24));
echo " ";
echo 'Days '.$days;
$months = floor($difference/(60*60*24*30));
echo 'Months '.$months;
$years = floor($difference/(60*60*24*365));
echo 'Years '.$years ;
echo " ";
在您回答之前,让我澄清一下,我的托管服务提供商不支持高于 5.2 的 PHP 版本,因此不要建议使用 diff 和间隔函数。
我收到警告:strtotime(( 期望参数 1 为字符串,请帮助。
$startdate
和$enddate
是 DateTime 对象,而不是字符串。 strtotime()
需要一个字符串,你应该简单地传递一个字符串,如下所示:
$startdate = "2013-11-15";
$enddate = "2013-11-20";
如果可能的话,我建议使用更高的PHP版本。 DateTime
类是您在PHP中处理时间和日期时的最佳方法。
我有一个函数可以做我认为你想要的。
你只需要把它传递给日期,它会告诉yu2之间的区别
function getDateDifference($start_date, $end_date) {
$diff = abs(strtotime($end_date) - strtotime($start_date));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
if($years == 1) {
$year_str = ' year';
}
else {
$year_str = ' years';
}
if($months == 1) {
$month_str = ' month';
}
else {
$month_str = ' months';
}
if($days == 1) {
$day_str = ' day';
}
else {
$day_str = ' days';
}
if($years == 0) {
if($months == 0) {
return $days.$day_str;
}
return $months.$month_str. ' '.$days.$day_str;
}
else {
return $years.$year_str.' '.$months.$month_str. ' '.$days.$day_str;
}
}
无需new DateTime
即可strtotime()
$timestamp_start = strtotime("2013-11-15");
$timestamp_end = strtotime("2013-11-20");