PHP - 计算两个日期之间的周数

PHP - calculating the number of weeks between two dates

我正在尝试计算两个日期之间的周数。下面的代码有 3 周的结果。然而,真的是4周。为什么会计算错误,如何解决?

我很想知道为什么这个特定代码不起作用,但也想知道是否有更好的方法。

我是 运行 PHP 7.2 版。下面是我正在使用的代码:

$HowManyWeeks = date( 'W', strtotime( 2019-04-21 23:59:00 ) ) - date( 'W', strtotime( 2019-03-25 00:00:00 ) );

$HowManyWeeks 的值应该是 4 但它显示为 3。

此外,当我在 https://phpfiddle.org/ 尝试该代码时,它给出了一个错误:

Line : 2 -- syntax error, unexpected '23' (T_LNUMBER), expecting ',' or ')'

但是在我的服务器上 运行 它显示 '3' 没有任何错误。

谢谢,

蒂姆

您可以使用 DateTime() 来实现:

$date1 = new DateTime('2017-04-30');
$date2 = new DateTime('2019-04-30');
// I have left the remainer. You may need to round up/down. 
$differenceInWeeks = $date1->diff($date2)->days / 7;
print_r($differenceInWeeks);

希望这对您有所帮助,

The value of $HowManyWeeks should be 4

为什么?请注意 php 一周是 begin with Monday,我在日历中计算,正好是 3。

如果需要4(星期日作为一周的第一天),勾选星期几

$time1 = strtotime('2019-04-21 23:59:00');
$week1 = idate('W', $time1);
if(idate('w', $time1) == 0) # Sunday, next week
    $week1++;
...

您传递给 strtotime 的日期需要用引号引起来。而正确答案确实是3,因为两次之间相隔了3周6天23小时59分钟。试试这个:

$HowManyWeeks = date( 'W', strtotime( '2019-04-21 23:59:00' ) ) - date( 'W', strtotime( '2019-03-25 00:00:00' ) );
echo $HowManyWeeks;

正如已经指出的那样,这只适用于同一年的星期。在@MiroslavGlamuzina 的回答中使用 DateTime 对象更容易,或者您可以简单地将 strtotime 差异除以 604800(一周中的秒数);如果需要转换为整数值,则可以使用 floorceil

$HowManyWeeks = (strtotime( '2019-04-21 23:59:00' ) - strtotime( '2019-03-25 00:00:00' )) / 604800;
echo $HowManyWeeks;

输出:

3.9939484126984

Demo on 3v4l.org