将字符串拆分为日期数组

时间:2015-05-23 01:21:26

标签: php arrays

我有一组时间戳,我从不同的XML文件导入。这就是它们的样子:

<field name="timestamp">2015-04-16T07:14:16Z</field>

所以我有一堆存储在名为$ timestamps的数组中,如下所示:

2015-04-16T07:14:16Z
2015-04-24T14:34:50Z
2015-04-25T08:07:24Z
2015-04-30T07:48:12Z
2015-05-02T08:37:01Z
2015-05-09T10:41:45Z
2015-05-01T07:27:21Z
2015-05-07T09:41:36Z
2015-05-12T04:06:11Z
2015-05-12T05:52:52Z
2015-05-12T11:28:16Z

我只对日期部分感兴趣,而不是时间。我尝试使用split()函数拆分字符串。

$dates = array();

for ($i=0; $i<count($timestamps); $i++){
        $dates = split ("T", $timestamps[$i]);
        echo $dates[$i] . "<br>"; 
    }

根据我的理解,它存储的是第一部分(在T之前),然后是T之后的部分。它如何只存储每个字符串的第一部分?

当我尝试这个时:

echo $dates[1];

它输出第一个日期罚款。我对其余部分不太确定。

有关更好方法的任何建议吗?

谢谢!

4 个答案:

答案 0 :(得分:3)

您应该使用strtotimedate,而不是字符串拆分和/或正则表达式。如果您的日期格式发生变化,这将有所帮助。

$dates = array();

foreach ($timestamps as $timestamp) {
    $d = strtotime($timestamp);
    $dates[] = date('Y-m-d', $d);
}

foreach ($dates as $date) {
    echo $date . '<br/>';
}

答案 1 :(得分:2)

我认为拆分并不是更好,最好是使用日期功能轻松获取日期。非常简单的代码: -

<?php
$dates = array('2015-04-16T07:14:16Z','2015-04-24T14:34:50Z','2015-04-25T08:07:24Z','2015-04-30T07:48:12Z','2015-05-02T08:37:01Z'); // i hope your dates array is like this

foreach($dates as $date){
    echo date('Y-m-d',strtotime($date)).'<br/>';
}
?>

输出: - http://prntscr.com/78b0x4

注意: - 我没有拿走你的整个阵列。因为在我的代码中很容易看到并理解我在做什么。感谢。

答案 2 :(得分:1)

您只需使用preg_replace()删除数组中的所有“时间”位:

$array = Array('2015-04-16T07:14:16Z', '2015-04-24T14:34:50Z', '2015-04-25T08:07:24Z');

// Remove "T" and anything after it
$output = preg_replace('/T.*/', '', $array);
print_r($output);

输出:

Array
(
    [0] => 2015-04-16
    [1] => 2015-04-24
    [2] => 2015-04-25
)

答案 3 :(得分:1)

没有理由将datestrotime拖入此中,这只是额外的开销。您已经有了预期的常规格式。

我还会发出关于使用日期功能的警告:根据您的服务器日期/ datestrtotime,您可能会遇到问题,这些值会发生变化时间(区域)设置!由于你的字符串没有指定时区偏移量,你甚至无法正确转换..你只需要随身携带服务器或自己选择一个。

确保实际值不会改变的更安全的方法是将其解析为字符串。分裂在&#34; T&#34;很好。您在如何处理变量方面遇到了麻烦。这是一个例子:

// example data
$timestamps =<<<EOT
015-04-16T07:14:16Z
2015-04-24T14:34:50Z
2015-04-25T08:07:24Z
2015-04-30T07:48:12Z
2015-05-02T08:37:01Z
2015-05-09T10:41:45Z
2015-05-01T07:27:21Z
2015-05-07T09:41:36Z
2015-05-12T04:06:11Z
2015-05-12T05:52:52Z
2015-05-12T11:28:16Z
EOT;
$timestamps=explode("\n",$timestamps);


$dates = array();
for ($i=0; $i<count($timestamps); $i++){
  $d = explode("T", $timestamps[$i]);
  $dates[] = $d[0];
}
print_r($dates);

输出:

Array
(
    [0] => 015-04-16
    [1] => 2015-04-24
    [2] => 2015-04-25
    [3] => 2015-04-30
    [4] => 2015-05-02
    [5] => 2015-05-09
    [6] => 2015-05-01
    [7] => 2015-05-07
    [8] => 2015-05-12
    [9] => 2015-05-12
    [10] => 2015-05-12
)