2016-06-26 394 views
-1

如何获得Date of MondayDate of Sunday如果我有mysqlDATETIME格式的具体日期?PHP如何获得给定日期下周的星期一和星期日的日期?

我想要得到本周的第一天的日期和给定日期下降的最后一天的日期。

我有日期'2016-06-05'它在'Y-m-d' 我想这样。

<?php 
$date = '2016-06-05'; 
echo date("Y-m-d", strtotime('monday this week', strtotime($date))), "\n"; 
echo date("Y-m-d", strtotime('sunday this week', strtotime($date))), "\n"; 
?> 

但它给人

2016-06-06 
2016-06-12 

这是不对的一周,它应该给

2016-05-30 
2016-06-05 

我甚至试过这样的方式。

$date = '2016-06-05'; 
echo date("Y-m-d", strtotime('monday', strtotime('this week', strtotime($date)))), "\n"; 
echo date("Y-m-d", strtotime('sunday', strtotime('this week', strtotime($date)))), "\n"; 

OR

$date = '2016-06-05'; 
echo date("Y-m-d", strtotime('monday', strtotime($date))), "\n"; 
echo date("Y-m-d", strtotime('sunday', strtotime($date))), "\n"; 

使用PHP 5.3

缺少什么我在这里?


UPDATE:

我想出了这一点,这是给予预期的输出。

function get_monday_sunday($date){ 
$dates_array = array(); 

    if(date('N', strtotime($date)) == 7){ 

    $dates_array['monday'] = date("Y-m-d", strtotime('Monday last week', strtotime($date))); 
    $dates_array['sunday'] = date("Y-m-d", strtotime('Sunday last week', strtotime($date))); 

    }else{ 

    $dates_array['monday'] = date("Y-m-d", strtotime('Monday this week', strtotime($date))); 
    $dates_array['sunday'] = date("Y-m-d", strtotime('Sunday this week', strtotime($date))); 
    } 
return $dates_array; 
} 

$date = '2016-06-05' 
print_r(get_monday_sunday($date)); 

看起来像当一天是星期的最后一天,然后下周重新开始,即php周开始是星期日我猜。

+0

echo date(“Y-m-d”,strtotime('上周日',strtotime($ date))),“\ n”;因为星期日是一周中的最后一天,在php – splash58

+0

谢谢,我有很多日期,它会在任何给定的日期工作吗? – AMB

+0

我不确定周日是第一天还是最后一天不是由服务器配置设置的。但在目前的环境下,它将起作用 – splash58

回答

3

在我制作的每个php项目中,我总是包含Carbon包。它扩展了DateTime类,并添加了一些非常好的功能,使日期工作变得更容易。

如果你会采取我的建议,你的代码会是这个样子:

$date = Carbon::parse($dateStringFromDb); 
echo $date->startOfWeek()->format('Y-m-d'); // monday 
echo $date->endOfWeek()->format('Y-m-d'); // sunday 

这真的是所有有给它。这就是我所说的“自我评论代码”!我打赌你实际上会喜欢用日期享受节目;-)

+0

谢谢,虐待它,现在我想出了丑陋的解决方案。 – AMB

相关问题