繁体   English   中英

一个月中每周的第一个日期

[英]First Date of Each Week in a Month

我遇到一个小问题,我有一个月(2013年12月)和星期数(1、2、3等),我需要找出每周的第一个日期。

我无法进行简单的搜索,例如找不到相对于日期的最接近的星期日,因为有些星期根本就不是从星期日开始的。

任何帮助,将不胜感激。

考虑到您的日期是每月1号:

  • 首先找到next Sunday
  • 然后一次添加1周,以获取下一个周日的

代码:

$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>';

输出:

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

你试一试

<?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>";
        }   
    }


 ?>

使用strtotime的第二个参数来指定日期,以便从以下日期计算“下一个星期日”和其他相对日期:

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

http://us2.php.net/strtotime

例:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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