PHP:日期之间的时间戳

时间:2011-04-18 12:19:53

标签: php arrays date timestamp

我有一个带时间戳的数组。如果此时间戳在两个给定日期之间,我需要将它们收集到另一个数组中。 让我举一个例子:

让我们说$ array1 []有:

Array ( [0] => 1299147500 [1] => 1299147453 [2] => 1299146476 [3] => 1299143220 [4] => 1297934349 [5] => 1297845742 [6] => 1297695551 [7] => 1296134251 [8] => 1295948452 [9] => 1295554308 [10] => 1295369389 [11] => 1295345559 [12] => 1295261432 [13] => 1295014784 [14] => 1294929846 [15] => 1294832875 )

我需要创建$ array2 [],其中包含来自$ array1 []的值,这些值介于2011年2月17日星期四至2011年3月3日星期四 我怎么能这样做?

非常感谢

4 个答案:

答案 0 :(得分:2)

$low = strtotime('Thursday February 17, 2011');
$high = strtotime('Thursday March 3, 2011');

$array2 = array();
foreach($array1 as $timestamp) {
    if ($low <= $timestamp && $timestamp <= $high) {
        $array2[] = $timestamp;
    }
}

使用array_filter替代维护密钥的替代方案。

$low = strtotime('Thursday February 17, 2011');
$high = strtotime('Thursday March 3, 2011');

$array2 = array_filter($array1, function($timestamp) use ($low, $high) {
    return $low <= $timestamp && $timestamp <= $high;
});

答案 1 :(得分:2)

  1. 使用strtotime()
  2. 将第一个和最后一个日期转换为时间戳
  3. 对于数组中的每个项目,如果它在min和max之间,则将其复制到第二个数组。 对时间戳数组进行排序

答案 2 :(得分:1)

http://codepad.org/mDvRJ534

<?php
$array1 = array(1299147500,1299147453,1299146476,1299143220,1297934349,1297845742,1297695551,1296134251,1295948452,1295554308,1295369389,1295345559,1295261432,1295014784,1294929846,1294832875);
$array2 = array();
$date1 = strtotime('Thursday February 17, 2011');
$date2 = strtotime('Thursday March 3, 2011');
foreach($array1 as $timestamp){
    if($timestamp <= $date2 && $timestamp >= $date1)
        $array2[] = $timestamp;
}
echo 'date1 = '.$date1."\n";
echo 'date2 = '.$date2."\n";
print_r($array2);

答案 3 :(得分:0)

有人在另一篇帖子中回答了这个问题How to check if a date is in a given range?