简体   繁体   中英

First Date of Each Week in a Month

I am having a small issue where I have the month (December 2013) and the Week Number (1, 2, 3 etc) and I need to find out the first date of each week.

I cannot do a simple search like finding the closest Sunday relative to a date since some weeks don't start on a Sunday at all.

Any help would be appreciated.

Considering you have the date of 1st of any month :

  • First find the next Sunday
  • Then add 1 week at a time to it to get subsequent Sunday's

Code :

$firstDayOfMonth = '2013-12-01';    // Try also with first day of other months

$week1 = $firstDayOfMonth;
$week2 = date( "Y-m-d" ,strtotime('next Sunday', strtotime( $week1 ) ) );
$week3 = date( "Y-m-d" ,strtotime('+1 week', strtotime( $week2 ) ) );
$week4 = date( "Y-m-d" ,strtotime('+1 week', strtotime( $week3 ) ) );
$week5 = date( "Y-m-d" ,strtotime('+1 week', strtotime( $week4 ) ) );

echo '
Week 1 starts on : ' .$week1 .'<br>
Week 2 starts on : ' .$week2 .'<br>
Week 3 starts on : ' .$week3 .'<br>
Week 4 starts on : ' .$week4 .'<br>
Week 5 starts on : ' .$week5 .'<br>';

Output :

Week 1 starts on : 2013-12-01
Week 2 starts on : 2013-12-08
Week 3 starts on : 2013-12-15
Week 4 starts on : 2013-12-22
Week 5 starts on : 2013-12-29

Just try

<?php

     $first_day_this_month = date('M-D-Y',strtotime(date('M-01-Y')));
     echo date('M-D-Y',strtotime(date('M-01-Y')))." = ".date('M-d-Y',strtotime(date('M-01-Y')));//First day of month
     echo "<br>";   
     $last_day_this_month  = date('t');//last day of month
     $last_day_num=intval($last_day_this_month);

    for($i=1;$i<$last_day_num;$i++)
    {

         $first_day_this_month = date('M-D-Y',strtotime(date('M-'.$i.'-Y')));//All day of month
         $dateopt_arr=date('M-N-Y',strtotime(date('M-'.$i.'-Y')));
        $dateo=explode('-',$dateopt_arr);
        //echo $dateo[1];
        if(($dateo[1]%7)==0)
        {
            echo $first_day_this_month = date('M-D-Y',strtotime(date('M-'.$i.'-Y')))." = ".date('M-d-Y',strtotime(date('M-'.$i.'-Y')));//Week day of month
            echo "<br>";
        }   
    }


 ?>

Use the second argument of strtotime to specify the date to calculate "next Sunday" and other relative dates from:

strtotime('next Sunday', strtotime('09/12/2013'));

http://us2.php.net/strtotime

Example:

echo date('m/d/Y', strtotime('next Sunday', strtotime('09/12/2013')));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM