PHP查找最接近时间线的日期
所以,嗯,好的.这可能是数学问题,所以希望你带上你的科学计算器;)
So, uh, ok. This might get mathematical, so hope you brought your scientific calculator with you ;)
这是我的问题:
给定一个初始日期(时间戳)、时间段(秒)和今天的日期(时间戳),我需要找到与 period*n 加上原始/初始日期重合的最近日期.
Given an initial date (timestamp), time period period (seconds) and today's date (timestamp), I need to find the nearest date which coincides with the period*n plus the original/initial date.
到目前为止,我得到了一些运行良好的东西,例如初始日期和最终(今天)日期之间的句点"数量,在上面的演示中为2":
So far, I got some stuff working nicely, such as the amount of "periods" between the initial and final(today's) date, which would be "2" in the demo above:
$initial=strtotime('2 April 1991');
$time=time();
$period=strtotime('+10 years',0);
$periods=round(($time-$initial)/$period);
接下来我做的是:
$range=$periods*$period;
最后:
echo date('d M Y',$initial+$range);
写的是2011 年 4 月 3 日".怎么到了3?(我怀疑这是闰年问题?)当你错过一些小东西时,你知道那种感觉吗?我现在感觉这一切都在我身上......
Which wrote '03 April 2011'. How did it get to 3? (I suspect it's a leap year issue?) You know that feeling when you're missing something small? I'm feeling it all over me right now....
推荐答案
好的,如果我理解你的要求,你想知道在给定时间段内发生的下一个日期(在你的情况下,每 10从 1991 年 4 月 2 日开始的年份,下一个日期是 2011 年 4 月 2 日).
Ok so if I understood what you are asking, you want to know the next date that will occurs in a given period of time (in your case, every 10 years starting from 2 April 1991, when will be the next date : 2 april 2011).
因此,您应该更深入地了解 DateTime 类在 PHP 中,日期更适合用于日期,因为它更准确.您将它与完全符合您需要的 DateInterval 混合:
So, you should take a deeper look at the DateTime class in PHP that is wayyyy better to use for the dates because it is more accurate. You mix it with DateInterval that match exactly what you need :
<?php
$interval = new DateInterval('P10Y'); // 10 years
$initial = new DateTime('1991-04-02');
$now = new DateTime('now');
while ($now->getTimestamp() > $initial->getTimestamp()) {
$initial = $initial->add($interval);
}
echo $initial->format('d M Y'); // should return April 2, 2011 !
?>
相关文章