dqn48247 2016-06-26 12:21
浏览 288

PHP如何获取给定日期的星期一和星期日的日期?

How can i get a Date of Monday and Date of Sunday if i have specific Date in mysql DATETIME format ?

i am trying to get the week's first day's date and last day's date in which the given date falls.

i have date '2016-06-05' its in 'Y-m-d' and i am trying it like this way.

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

but its giving

2016-06-06
2016-06-12

which is wrong week, it should give

2016-05-30
2016-06-05

i even tried like this way.

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

OR

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

using PHP 5.3

what am i missing here ?


UPDATE:

i came up with this, this is giving expected output.

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));

looks like when the day is last day of week, then next week starts over, i.e. php week start is sunday i guess.

  • 写回答

1条回答 默认 最新

  • douchun5969 2016-06-26 13:04
    关注

    In every single php project I make, I always include the Carbon package. It extends the DateTime class and adds some very nice functionality that makes working with dates a lot easier.

    If you would take my suggestion, your code would look something like this:

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

    And that is really all there is to it. This is what I call "self commenting code"! I bet you're actually going to enjoy program with dates ;-)

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条