PHP:根据固定基准日期获取下一个日期 [英] PHP: get next date based on fixed base date

查看:58
本文介绍了PHP:根据固定基准日期获取下一个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP中是否有一种方法可以使用从给定日期开始的4周间隔来获取下一个日期?

is there a way in PHP to get the next date(s) using a 4-week interval from a given date ?

示例:

我的开始日期是2014年1月3日,星期五,我的时间间隔是从该日期起每4周一次.我正在寻找的是与该4周间隔相匹配的当前日期的下一个日期(或日期,如果可能的话).在上面的示例中,这将是2014年5月23日(星期五)(然后是2014年6月20日,2014年7月18日等).

My start date is Friday, Jan 03, 2014 and my interval is every 4 weeks from that date. What I am looking for is the next date (or dates, if possible) from the current date that matches this 4-week interval. In the above example this would be Friday, May 23, 2014 (then June 20, 2014, July 18, 2014 etc.).

我知道我可以获得如下所示的当前日期: $ today = date('Y-m-d');

I know I can get the current date as follows: $today = date('Y-m-d');

我可能可以这样设置开始日期: $ start = date('2014-01-03');

and I could probably set the start date like this: $start = date('2014-01-03');

但是我不知道如何计算间隔以及如何找出下一个匹配的日期.

but I don't know how to calculate the interval and how to find out the next matching date(s).

推荐答案

您应该阅读DateTime类,特别是 DateInterval :

You should read up on the DateTime classes, specifically DatePeriod and DateInterval:

$start = new DateTime('2014-01-03');
$interval = DateInterval::createFromDateString('4 weeks');
$end = new DateTime('2015-12-31');

$occurrences = new DatePeriod($start, $interval, $end);

foreach ($occurrences as $occurrence) {
    echo $occurrence->format('Y-m-d') . PHP_EOL;
}

DatePeriod 需要一个开始日期和一个 DateInterval ,并允许您遍历对象以使用给定的间隔获取边界内的所有日期.截止日期可以是设置的周期数(因此是下一个10个日期),也可以是结束日期(如上),即使结束日期不是间隔所在的日期之一(它将在其下方停止).或者,您可以使用 8601间隔符号字符串(听起来很有趣,是吧?),但是我对此感到很不稳定.

DatePeriod takes a start date and a DateInterval and allows you traverse over the object to get all dates within the boundaries using the given interval. The cut off can be either a set number of cycles (so the next 10 dates) or an end date (like above), even if the end date is not one of the dates the interval falls on (it will stop below it). Or you can use an 8601 interval notation string (which sounds so much fun, huh?), but I'm pretty shaky on that.

这篇关于PHP:根据固定基准日期获取下一个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆