PHP查找距离时间轴周期最近的日期 [英] PHP Find date nearest to a timeline period

查看:242
本文介绍了PHP查找距离时间轴周期最近的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,嗯,好的。这可能会得到数学,所以希望你带你的科学计算器;)



这是我的问题:





给定初始日期(时间戳),时间段(秒)和今天的日期(时间戳),我需要找到与* n加上原始/初始日期一致的最近日期。



到目前为止,我收到了一些很好的工作,比如初始和最后(今天)之间的期间数量,在上面的演示中将是2:

  $ initial = strtotime('1991年4月2日'); 
$ time = time();
$ period = strtotime('+ 10年',0);

$ periods = round(($ time- $ initial)/ $ period);

我做的下一件事是:

  $ range = $ periods * $ period; 

最后:

回显日期('d M Y',$ initial + $ range); 

哪个写了'03四月2011'。它是如何达到3? (我怀疑这是一个闰年吗?)
你知道,当你缺少一些小的东西吗?我现在感觉到这一切都在我身上。

解决方案

好吧,如果我明白你在问什么,你想知道在给定时间段内发生的下一个日期(在您的情况下,从1991年4月2日起,每10年,将在下一个日期:2011年4月2日)。



所以,您应该深入了解 DateTime DateInterval 进行混合:

 <?php 
$ interval = new DateInterval('P10Y'); // 10年
$ 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'); //应该返回2011年4月2日!
?>


So, uh, ok. This might get mathematical, so hope you brought your scientific calculator with you ;)

This is my problem:

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.

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);

The next thing I did was:

$range=$periods*$period;

And finally:

echo date('d M Y',$initial+$range);

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....

解决方案

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).

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 !
?>

这篇关于PHP查找距离时间轴周期最近的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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