星期六星期开始时的周数

时间:2017-04-13 02:43:59

标签: php algorithm date

如何根据星期六作为星期开始日(星期六 - 星期五)找到周数?我一直在努力解决这个问题。 PHPsolution将不胜感激,但任何语言的任何例子都可以。

我的公司工作周是从星期六(第1天)到星期五(第7天),我需要能够显示周数(如52/53的第23周)。我可能会感到困惑,正常Date('W', $time)函数给出的周数就足够了,但我对此表示怀疑。

我在Excel中找到了可能的解决方案,但是我很长时间没有完成VBA,并且无法做出same docs的正面或反面。

1 个答案:

答案 0 :(得分:0)

这些功能似乎可以解决我的问题,但可能需要测试更远的年份:

// The N option gives the normal week day, arithmetic makes it return my custom week days
function getDayOfWeek(\DateTimeImmutable $date)
{
    return ($date->format('N') + 2) % 7;
}

function getWeekNumber(\DatetimeImmutable $date)
{
    // Recursive function that loops through every day until it gets the start of a week
    $startOfWeek = function (\DateTimeImmutable $date) use (&$startOfWeek) {
        return (getDaysOfWeek($date) === 1)
            ? $date : $startOfWeek($date->modify('+1 day'));
    };

    // The z option tells us what day of the year this is, 
    // not a 100% sure this step is necessary
    if (getDayOfWeek($date === 1) {
        $nbDays = $date->format('z');
    else {
        $nbDays = $startOfWeek($date->modify('-7 days'))->format('z');
    }

    // Divides by the number of days in a week to get the number of weeks
    return ceil($nbDays / 7);
}
相关问题