我想计算两个日期之间的周数,天数。
例如:2013-12-25
到2013-12-25
将输出1 Day
例如:2013-12-22
到2013-12-25
将输出4 Days
例如:2013-12-18
到2013-12-25
将输出1 Week, 1 Day
例如:2013-12-18
到2013-12-26
将输出1 Week, 2 Days
例如:2013-12-16
到2013-12-30
将输出2 Weeks, 1 Day
我尝试使用How to calculate the difference between two dates using PHP?
但它似乎无法正常工作
由于
答案 0 :(得分:1)
我认为最好的方法是使用时间戳,然后你可以计算两个日期之间的秒数,然后将其转换为几天和几周。
example:
$time1; // contains seconds since 1970
$time2;
$diff=$time2-$time1;
$days=($diff % 604800)/86400;
$weeks=($diff-($days*86400))/604800;
echo $weeks $days;
答案 1 :(得分:1)
使用DateTime :: diff()函数
示例:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
将输出:
+2 days
有关详细信息,请查看this页
答案 2 :(得分:1)
如果您希望仅在几周和几天内显示差异,请使用此功能:
function diff_in_weeks_and_days($from, $to) {
$day = 24 * 3600;
$from = strtotime($from);
$to = strtotime($to) + $day;
$diff = abs($to - $from);
$weeks = floor($diff / $day / 7);
$days = $diff / $day - $weeks * 7;
$out = array();
if ($weeks) $out[] = "$weeks Week" . ($weeks > 1 ? 's' : '');
if ($days) $out[] = "$days Day" . ($days > 1 ? 's' : '');
return implode(', ', $out);
}
echo diff_in_weeks_and_days('2013-12-18', '2013-12-26'); # 1 Week, 2 Days