phparraysdatetimesanitization

Remove the time substring from an array of datetime strings


I have an array of timestamps that I'm importing from different XML files. This is how they look like:

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

So I have a bunch of them stored in an array named $timestamps like this:

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

I am only interested in the date part, not the time. I have tried splitting the string using the split() function.

$dates = array();

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

From what I understand it is storing the first part (before the T) then the part after the T. How can it store only the first part of each string?

When I try this:

echo $dates[1];

it outputs the first date fine. I'm not quite sure about the rest.


Solution

  • I think splitting is not better the best is get date using date function easily. Very easy code:-

    <?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/>';
    }
    ?>
    

    Output:- http://prntscr.com/78b0x4

    Note:-I didn't take your whole array. Because it's easy to see and understand what i am doing there in my code. thanks.