使用 PHP 获取未来的特定日期


geting specific dates in the future with php

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

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

所以我拥有的是这样的:

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

然后,从这个链接堆栈溢出使用这个函数,我得到了我的start_date是:(即:"第一个星期一")

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
)

据我了解,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

strtotime(),它适用于今天的参考。

strtotime("+x days");

斯特托时间

如果您需要与另一个日期有关的内容...

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