简体   繁体   中英

Formatting JSON datetime to PHP inside foreach loop

I am building an event section for a client. Using JSON and PHP, I'm able to pull in all the data perfectly.

What I'm having trouble on is formatting the date correctly inside the foreach loop. Currently I've set it to get today's date for now, but I know that's pointless as each event shows today's date.

Here's a sample of the structure code:

<?php 
$json = file_get_contents("http://api.bandsintown.com/artists/Skrillex/events.json?api_version=2.0&app_id=SAMPLE");
$data = json_decode($json);                                      
$datetime = new DateTime();                              

foreach($data as $events) {
    echo "<td class='bit-venue'>" . $events->venue->name . "</td>"; 
    echo $datetime->format('M j, d');
}
?>  

I know I'm missing something, so any help would be greatly appreciated.

Edit: Working solution:

Got it working.

I changed $datetime->format('M j, d') to date('M j, d', strtotime($events->datetime))

I knew I needed to invoke the datetime string, but just was not sure how to go about that in the foreach loop.

Credit goes to Bilal who's answer disappeared for some reason.

So your code should be like this

<?php 
$json = file_get_contents("http://api.bandsintown.com/artists/Skrillex/events.json?   api_version=2.0&app_id=SAMPLE");
$data = json_decode($json);                                      
$format = 'Y-m-dTH:i:s';                              

foreach($data as $events) {
    echo "<td class='bit-venue'>" . $events->venue->name . "</td>";

    $date = DateTime::createFromFormat($format, $events->datetime);
    echo $date->format('Y-m-d H:i:s');
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM