从日期时间字符串数组中删除时间子字符串[重复]

问题描述 投票:0回答:4

我有一个从不同 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];

它可以很好地输出第一个日期。其余的我不太确定。

php arrays datetime sanitization
4个回答
3
投票

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

$dates = array();

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

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

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

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


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
)

1
投票

没有理由将

date
strotime
拖入其中,这只是额外的开销。 您已经有了预期的常规格式。

我还会对使用日期函数发出警告:根据服务器的日期/时间(区域)设置,将它们放入

date
strtotime
后,您可能会遇到值更改的问题!由于您的字符串没有指定时区偏移量,因此您甚至无法正确转换..您只需使用服务器所在的位置或自己选择一个即可。

确保实际值不改变的更安全方法是将其解析为字符串。 在“T”处分开就可以了。您只是在如何处理变量方面遇到了麻烦。这是一个例子:

// 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
)
© www.soinside.com 2019 - 2024. All rights reserved.