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:32
$givenday = date("w", mktime(0, 0, 0, MM, dd, yyyy));

This gives you the day of the week of the given date itself where 0 = Sunday and 6 = Saturday. From there you can simply calculate backwards to the day you want.

查看更多
只靠听说
3楼-- · 2019-01-01 07:32

This is the shortest and most readable solution I found:

    <?php
    $weekstart = strtotime('monday this week');
    $weekstop = strtotime('sunday this week 23:59:59');
    //echo date('d.m.Y H:i:s', $weekstart) .' - '. date('d.m.Y H:i:s', $weekstop);
    ?>

strtotime is faster than new DateTime()->getTimestamp().

查看更多
心情的温度
4楼-- · 2019-01-01 07:33
<?php
/* PHP 5.3.0 */

date_default_timezone_set('America/Denver'); //Set apprpriate timezone
$start_date = strtotime('2009-12-15'); //Set start date

//Today's date if $start_date is a Sunday, otherwise date of previous Sunday
$today_or_previous_sunday = mktime(0, 0, 0, date('m', $start_date), date('d', $start_date), date('Y', $start_date)) - ((date("w", $start_date) ==0) ? 0 : (86400 * date("w", $start_date)));

//prints 12-13-2009 (month-day-year)
echo date('m-d-Y', $today_or_previous_sunday);

?>

(Note: MM, dd and yyyy in the Question are not standard php date format syntax - I can't be sure what is meant, so I set the $start_date with ISO year-month-day)

查看更多
与风俱净
5楼-- · 2019-01-01 07:33

Here is what I am using...

$day = date('w');
$week_start = date('m-d-Y', strtotime('-'.$day.' days'));
$week_end = date('m-d-Y', strtotime('+'.(6-$day).' days'));

$day contains a number from 0 to 6 representing the day of the week (Sunday = 0, Monday = 1, etc.).
$week_start contains the date for Sunday of the current week as mm-dd-yyyy.
$week_end contains the date for the Saturday of the current week as mm-dd-yyyy.

查看更多
听够珍惜
6楼-- · 2019-01-01 07:35

If you want Monday as the start of your week, do this:

$date = '2015-10-12';
$day = date('N', strtotime($date));
$week_start = date('Y-m-d', strtotime('-'.($day-1).' days', strtotime($date)));
$week_end = date('Y-m-d', strtotime('+'.(7-$day).' days', strtotime($date)));
查看更多
弹指情弦暗扣
7楼-- · 2019-01-01 07:35

What about:

$date = "2013-03-18"; 
$searchRow = date("d.m.Y", strtotime('last monday',strtotime($date." + 1 day")));
echo "for date " .$date ." we get this monday: " ;echo $searchRow; echo '<br>';

Its not the best way but i tested and if i am in this week i get the correct monday, and if i am on a monday i will get that monday.

查看更多
登录 后发表回答