Get first day of week in PHP?

2019-01-01 06:52发布

Given a date MM-dd-yyyy format, can someone help me get the first day of the week?

标签: php datetime
30条回答
萌妹纸的霸气范
2楼-- · 2019-01-01 07:22

Another way to do it....

$year = '2014';
$month = '02';
$day = '26';

$date = DateTime::createFromFormat('Y-m-d H:i:s', $year . '-' . $month . '-' . $day . '00:00:00');
$day = date('w', $date->getTimestamp());

// 0=Sunday 6=Saturday
if($day!=0){

   $newdate = $date->getTimestamp() - $day * 86400;  //86400 seconds in a day

   // Look for DST change 
   if($old = date('I', $date->getTimestamp()) != $new = date('I', $newdate)){
       if($old == 0){
           $newdate -= 3600;  //3600 seconds in an hour
       } else {
           $newdate += 3600;
       }
   }

   $date->setTimestamp($newdate);
}

echo $date->format('D Y-m-d H:i:s');
查看更多
无色无味的生活
3楼-- · 2019-01-01 07:22

Keep it simple :

<?php    
$dateTime = new \DateTime('2012-05-14');
$monday = clone $dateTime->modify(('Sunday' == $dateTime->format('l')) ? 'Monday last week' : 'Monday this week');
$sunday = clone $dateTime->modify('Sunday this week');    
?>

Source : PHP manual

查看更多
忆尘夕之涩
4楼-- · 2019-01-01 07:22

How about this?

$first_day_of_week = date('m-d-Y', strtotime('Last Monday', time()));
$last_day_of_week = date('m-d-Y', strtotime('Next Sunday', time()));
查看更多
高级女魔头
5楼-- · 2019-01-01 07:23
$monday = date('d-m-Y',strtotime('last monday',strtotime('next monday',strtotime($date))));

You have to get next monday first then get the 'last monday' of next monday. So if the given date is monday it will return the same date not last week monday.

查看更多
残风、尘缘若梦
6楼-- · 2019-01-01 07:23

I found this solution helpful. Just subtract if it isn't monday to get the previous Monday. I am using $lower_date as the date I pulled from a query that I then need to reconcile to the previous Monday.

//set this up to go backwards until you find monday
while(date('D',strtotime($lower_date))!='Mon'){
    $lower_date = date('Y-m-d', strtotime($lower_date . ' - 1 day')); //increase the upper spec
}
查看更多
像晚风撩人
7楼-- · 2019-01-01 07:23
strtotime('this week', time());

Replace time(). Next sunday/last monday methods won't work when the current day is sunday/monday.

查看更多
登录 后发表回答