php - 如何在同一周内找到两个时间戳?

时间:2017-03-13 18:12:19

标签: php timestamp

我有两个时间戳。我只想检查它们是否在同一周内。我知道我可以使用

if(date('w',$one)==date('w',$two)) {}

但问题是它可能会回响2018年12月27日和2019年1月1日的不同值。这些天可能在同一周,但一年中的周数不同,这就是为什么它不能是一个可靠的解决方案 如果您提供IntlCalendar类的解决方案,那将是非常棒的,因为我的客户希望星期的开始日是星期六。

2 个答案:

答案 0 :(得分:2)

刚试过,它猜测这是有效的。这是一个例子(对https://secure.php.net/manual/en/function.date.php btw有一个很好的解释。):

$firstDate = strtotime('2016-12-31');
$secondDate = strtotime('2017-01-01');

//both days are in the same week (number 52 of 2016)
echo date('oW', $firstDate)  . "\n"; //201652
echo date('oW', $secondDate) . "\n"; //201652

//week has to be the same, but also the calendar year, so
echo date('Y', $firstDate)  . "\n"; //2016
echo date('Y', $secondDate) . "\n"; //2017

//if we check both oW AND Y date than we can test wheter 2 days fall within the same week of the same year
$firstDate = strtotime('2016-12-31'); // = Friday of "last" week of 2016
$secondDate = strtotime('2017-01-01'); // = Sunday of "last" week of 2016
$result = date('oW', $firstDate) === date('oW', $secondDate) && date('Y', $firstDate) === date('Y', $secondDate);
var_dump($result); // false (week is the same, but year is different)

$firstDate = strtotime('2017-01-01'); // = Sunday, so still "last" week of 2016
$secondDate = strtotime('2017-01-02'); // = Monday, so first week of 2017
$result = date('oW', $firstDate) === date('oW', $secondDate) && date('Y', $firstDate) === date('Y', $secondDate);
var_dump($result); // false (year is the same, but week is different)

$firstDate = strtotime('2016-12-30');
$secondDate = strtotime('2016-12-31');
$result = date('oW', $firstDate) === date('oW', $secondDate) && date('Y', $firstDate) === date('Y', $secondDate);
var_dump($result); // true (same week, same year)

答案 1 :(得分:0)

我猜你总是可以把一个日期时间(过去更多的那个)作为参考,计算最大偏移量(直到当前周末),然后比较日期:

<?php

function same_week($s_ref, $s){
    $d_ref = new DateTime($s_ref);
    $d = new DateTime($s);

    $dow = $d_ref->format('w');
    //if the reference is a Saturday, shift one week, otherwise shift
    //until the next Saturday
    $delta = ($dow == 6)?7:(6 - $dow);

    $d_ref->modify("+$delta days midnight");
    return ($d < $d_ref);
}

var_dump(same_week('2018-12-28 12:00:00', '2018-12-29 00:00:00')); //false
var_dump(same_week('2018-12-29 12:00:00', '2019-01-04 10:00:00')); //true
?>