如何获取周开始日期星期日和星期六结束日期星期六在PHP

时间:2022-09-26 11:15:07

How to get week start date Sunday and week end date Saturday in php.

如何获取周开始日期星期日和星期六结束日期星期六在PHP。

I try my self below to code am getting Week Start Date as Monday Week End Date as Sunday.

我在下面尝试自己编码将周开始日期作为星期一周结束日期作为星期日。

$cdate = date("Y-m-d");
$week =  date('W', strtotime($cdate));
$year =  date('Y', strtotime($cdate));      
$firstdayofweek = date("Y-m-d", strtotime("{$year}-W{$week}+1"));
$lastdayofweek = date("Y-m-d", strtotime("{$year}-W{$week}-7"));

Thanks, Vasanth

3 个解决方案

#1


Here is a solution using DateTime, which is a little bit nicer to work with than date and strtotime :) :

这是一个使用DateTime的解决方案,这比使用date和strtotime更好一些:):

$today = new \DateTime();
$currentWeekDay = $today->format('w'); // Weekday as a number (0 = Sunday, 6 = Saturday)

$firstdayofweek = clone $today;
$lastdayofweek  = clone $today;

if ($currentWeekDay !== '0') {
    $firstdayofweek->modify('last sunday');
}

if ($currentWeekDay !== '6') {
    $lastdayofweek->modify('next saturday');
}

echo $firstdayofweek->format('Y-m-d').PHP_EOL;
echo $lastdayofweek->format('Y-m-d').PHP_EOL;

#2


Change your local configuration :

更改本地配置:

setlocale('LC_TIME', 'fr_FR.utf8');

Change 'fr_FR.utf8' by your local.

由您当地更改'fr_FR.utf8'。

#3


I changed my code like below. This code is correct ? but it's worked for me.

我改变了我的代码,如下所示。这段代码是对的吗?但它对我有用。

$cdate = date("Y-m-d");
$week =  date('W', strtotime($cdate));
$year =  date('Y', strtotime($cdate));      
echo "<br>".$firstdayofweek = date("Y-m-d", strtotime("{$year}-W{$week}-0"));
echo "<br>".$lastdayofweek = date("Y-m-d", strtotime("{$year}-W{$week}-6"));

#1


Here is a solution using DateTime, which is a little bit nicer to work with than date and strtotime :) :

这是一个使用DateTime的解决方案,这比使用date和strtotime更好一些:):

$today = new \DateTime();
$currentWeekDay = $today->format('w'); // Weekday as a number (0 = Sunday, 6 = Saturday)

$firstdayofweek = clone $today;
$lastdayofweek  = clone $today;

if ($currentWeekDay !== '0') {
    $firstdayofweek->modify('last sunday');
}

if ($currentWeekDay !== '6') {
    $lastdayofweek->modify('next saturday');
}

echo $firstdayofweek->format('Y-m-d').PHP_EOL;
echo $lastdayofweek->format('Y-m-d').PHP_EOL;

#2


Change your local configuration :

更改本地配置:

setlocale('LC_TIME', 'fr_FR.utf8');

Change 'fr_FR.utf8' by your local.

由您当地更改'fr_FR.utf8'。

#3


I changed my code like below. This code is correct ? but it's worked for me.

我改变了我的代码,如下所示。这段代码是对的吗?但它对我有用。

$cdate = date("Y-m-d");
$week =  date('W', strtotime($cdate));
$year =  date('Y', strtotime($cdate));      
echo "<br>".$firstdayofweek = date("Y-m-d", strtotime("{$year}-W{$week}-0"));
echo "<br>".$lastdayofweek = date("Y-m-d", strtotime("{$year}-W{$week}-6"));