How to set the “first day of the week” to Thursday in PHP

隐身守侯 提交于 2020-12-02 06:59:47

问题


I want to set the first day of the week to Thursday (not Sunday or Monday), because it's the company's cut-off date.

I already have a code to determine the current week number of a date but it starts in Sunday or Monday.

How to modify these to my preference?

function findweek($date) {
    $monthstart=date("N",strtotime(date("n/l/Y",strtotime($date))));
    $newdate=(date("j",strtotime($date))+$monthstart)/7;
    $ddate=floor($newdate);
    if($ddate != $date) {
        $ddate++;
    }
    return $ddate;
}

回答1:


http://php.net/manual/en/datetime.formats.relative.php says that as of PHP version 5.6.23, 7.0.8 "Weeks always start on monday. Formerly, sunday would also be considered to start a week." That said, is your problem that the number of weeks returned might be incorrect depending on whether today falls on or before Thursday of the current week? Maybe try something like this:

$date = new DateTime();
$week = intval($date->format('W'));
$day = intval($date->format('N'));
echo $day < 4 ? $week-1 : $week;

If subtracting 1 isn't the answer you could play around with addition/subtraction, comparing the result with the actual answer you know to be true until you get the right formula. Hope this helps!




回答2:


This should work.

function findweek($date, $type = "l") {
    $time = strtotime($date);
    return date($type, mktime(0, 0, 0, date("m", $time) , date("d", $time)-date("d", $time)+1, date("Y", $time)));
}

echo findweek('2015-09-16');


来源:https://stackoverflow.com/questions/32577104/how-to-set-the-first-day-of-the-week-to-thursday-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!