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:42

The following code should work with any custom date, just uses the desired date format.

$custom_date = strtotime( date('d-m-Y', strtotime('31-07-2012')) ); 
$week_start = date('d-m-Y', strtotime('this week last monday', $custom_date));
$week_end = date('d-m-Y', strtotime('this week next sunday', $custom_date));
echo '<br>Start: '. $week_start;
echo '<br>End: '. $week_end;

I tested the code with PHP 5.2.17 Results:

Start: 30-07-2012
End: 05-08-2012
查看更多
忆尘夕之涩
3楼-- · 2019-01-01 07:44

Given PHP version pre 5.3 following function gives you a first day of the week of given date (in this case - Sunday, 2013-02-03):

<?php
  function startOfWeek($aDate){
    $d=strtotime($aDate);
    return strtotime(date('Y-m-d',$d).' - '.date("w",$d).' days');
  }

  echo(date('Y-m-d',startOfWeek("2013-02-07")).'
');
?>
查看更多
路过你的时光
4楼-- · 2019-01-01 07:44

I found this quite frustrating given that my timezone is Australian and that strtotime() hates UK dates.

If the current day is a Sunday, then strtotime("monday this week") will return the day after.

To overcome this:

Caution: This is only valid for Australian/UK dates

$startOfWeek = (date('l') == 'Monday') ? date('d/m/Y 00:00') : date('d/m/Y', strtotime("last monday 00:00"));
$endOfWeek = (date('l') == 'Sunday') ? date('d/m/Y 23:59:59') : date('d/m/Y', strtotime("sunday 23:59:59"));
查看更多
刘海飞了
5楼-- · 2019-01-01 07:44

Assuming Monday as the first day of the week, this works:

echo date("M-d-y", strtotime('last monday', strtotime('next week', time())));
查看更多
只若初见
6楼-- · 2019-01-01 07:44

Just use date($format, strtotime($date,' LAST SUNDAY + 1 DAY'));

查看更多
妖精总统
7楼-- · 2019-01-01 07:45

The easiest way to get first day(Monday) of current week is:

strtotime("next Monday") - 604800;

where 604800 - is count of seconds in 1 week(60*60*24*7).

This code get next Monday and decrease it for 1 week. This code will work well in any day of week. Even if today is Monday.

查看更多
登录 后发表回答