使用 php 获取未来的具体日期

geting specific dates in the future with php

所以我的问题很简单,但解决方案一直在逃避我。我正在尝试以设定的时间间隔获取未来日期的列表,该时间间隔尊重月中的周 nr 和周中的天 nr。例如,我需要列出相隔 3 个月的第 2 个星期一的日期。

我有一个表格,用户可以在其中指定 2 个日期和时间间隔。

所以我有这样的东西:

$start_date = "2015-01-07";
$end_date = "2016-01-07";
$period = "+1 month";

然后,使用此 link Whosebug 中的函数,我得到了我的 start_date 的周数:(即:"first monday")

function literalDate($timestamp) {
    $timestamp = is_numeric($timestamp) ? $timestamp : strtotime($timestamp);
    $weekday = date('l', $timestamp);
    $month = date('M', $timestamp);

$ord = 1;

while(date('M', ($timestamp = strtotime('-1 week', $timestamp))) == $month) {
    $ord++;
}

$lit = array(null, 'first', 'second', 'third', 'fourth', 'fifth');

return $lit[$ord].' '.$weekday;
}
$day_number = literalDate($start_date);
$list=array();

然后。我正在尝试这样做

while(strtotime($start_date) <= strtotime($end_date))
{
  $list[]=$start_date;
  $start_date=date('Y-m-d', strtotime("$start_date $period"));
  $month = date('F', strtotime($start_date));
  $start_date = date('Y-m-d', strtotime($day_number.' of '.$month)); //this always returns 1970-01-01
}

print_r($list);

如评论中所述,我的预期输出类似于

array(
[0] => 2015-01-07
[1] => 2015-02-04
[2] => 2015-03-04
[3] => 2015-04-01
[4] => 2015-05-06
[5] => 2015-06-03
[6] => 2015-07-01
[7] => 2015-08-05
[8] => 2015-09-02
[9] => 2015-10-07
[10] => 2015-11-04
[11] => 2015-12-02
)

strtotime() 在今天的参考中起作用。

strtotime("+x days");

strtotime

如果您需要与其他日期相关的内容...

date("Y-m-d", strtotime($yourdate) + 86400 * $days);

据我了解,DateInterval 应该能满足您的需求:

$start    = new DateTime('2015-01-07');
$start->modify('first day of this month');
$end      = new DateTime('2016-01-07');
$end->modify('first day of this month');
$interval = DateInterval::createFromDateString('first wednesday');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
    $d = $dt->format("d");
    if($d <= 7){
       echo $dt->format("Y-m-d") . "\n";
    }
}

将显示:

2015-01-07
2015-02-04
2015-03-04
2015-04-01
2015-05-06
2015-06-03
2015-07-01
2015-08-05
2015-09-02
2015-10-07
2015-11-04
2015-12-02
2016-01-06