用strtotime()和date()函数算出2019年9月的周日日期

strtotime---用于接收两个参数,第一个参数是格式化的日期数据如:date('Y-m-d'),第二个参数有如'+7 day'

  • 函数版
<?php
$firstsunday = strtotime(date('Y-m-01'));
$thisy = intval(date('m'));
$diffdays=0;
$count = 0;
if (date('w',strtotime(date('Y-m-01')))!=0)
{
      $diffdays=7-date('w',strtotime(date('Y-m-01')));
}
else{
    $count++;
}
$startdate =strtotime(date('Y-m-01')."+".$diffdays."day");
while (True)
{
    if ($thisy!=intval(date('m',$startdate)))
    {
            break;
    }
    echo date('Y-m-d',$startdate)."
";
    $startdate = strtotime(date('Y-m-d',strtotime(date('Y-m-d',$startdate)."+7 day")));
    //
}

结果

2019-09-01
2019-09-08
2019-09-15
2019-09-22
2019-09-29
  •  类版本---date()的参数可以是‘2019-09-20’这样的字符串,如同date('2019-09-20')或者是strtotime返回的整型数如同date('Y-m-d',strtotime('2019-09-20))
class mycalendar
{
    function __construct($year,$mon)
    {
        $this->nianyue=$year.'-'.$mon.'-'.'01';
        $this->firstday=strtotime(date($this->nianyue));
        $this->m = intval(date('m',$this->firstday));
        $this->wdaylist=array();
        echo "时间戳:".date('Y-m-d',$this->firstday)."
";
    }
    function startday()
    {
        $w = date('w',$this->firstday);
        $diffdays=0;
        if ($w!=0)
        {
            $diffdays= 7-$w;
        }
        $this->firstday = strtotime(date('Y-m-d',strtotime($this->nianyue))."+".$diffdays." day");
        //array_push($this->wdaylist,$w);
        //echo "
".date('Y-m-d',$this->firstday);
        //echo "
".$this->firstday;
        return $this->firstday;
    }
    function addwday()
    {
        $curday = $this->startday();
        while (true){
            if(intval(date('m',$curday)!=$this->m))
            {
                break;
            }
            echo date('Y-m-d',$curday)."
";
            array_push($this->wdaylist,date('Y-m-d',$curday));
            $curday=strtotime(date('Y-m-d',$curday)."+7 day");
        }
        return $this->wdaylist;
    }
}
$mycal = new mycalendar(2019,10);
var_dump($mycal->addwday());

结果:

时间戳:2019-10-01
2019-10-06
2019-10-13
2019-10-20
2019-10-27
array(4) {
  [0]=>
  string(10) "2019-10-06"
  [1]=>
  string(10) "2019-10-13"
  [2]=>
  string(10) "2019-10-20"
  [3]=>
  string(10) "2019-10-27"
}

  •  计算月末最后一天
echo date('Y-m-d',strtotime(date('2019-10-01')."+1 month -1 day"));

输出结果:

2019-10-31
  •  注意!对于日期计算一定要,正确的使用参数,否则将会出错
$lastday = strtotime(date('Y-m-d',$this->time)."+1 day");#正确
$lastday = strtotime(date($this->time)."+1 day");#错误,这样会返回1970-01-01
原文地址:https://www.cnblogs.com/saintdingspage/p/11561246.html