最近的日期在php strtotime

时间:2016-12-14 22:07:42

标签: php date

我在变量中有几个日期(strtotime),并希望使用php在指定日期(我的日期)之后的第一个最近的日期。我该怎么办?

可变

$varD = "1481691600,1482642000,1482037200";

我的约会对象:

1481778000 => (2016-12-15)

几个日期(strtotime):

1481691600 => (2016-12-14)
1482642000 => (2016-12-25)
1482037200 => (2016-12-18) //result

结果:

1482037200 => (2016-12-18)

1 个答案:

答案 0 :(得分:1)

$varD = "1481691600,1482037200,1482642000";
$myDate = "1481778000";

explode时间戳字符串($varD)之后,您可以过滤它们并返回结果的最小值。以下是使用array_filtermin进行此操作的一种方法。

$comp = function($x) use ($myDate) { return $x > $myDate; };

$firstDateAfterYours = min(array_filter(explode(',', $varD), $comp));

但是如果你已经知道字符串中的时间戳将按升序排列,那么将整个事物转换为数组并对其进行排序可能会更快。您可以使用strtok逐个浏览它,只要达到大于目标的时间戳就停止。

$ts = strtok($varD, ',');
while ($ts !== false) {
    $ts = strtok(',');
    if ($ts > $myDate) break;
}
$firstDateAfterYours = $ts;