-2

I need to format the date time to a more readable format for instance a format, something like:- '23rd September 2018 17.00'

//Json Array

instances": [
{
"start": "2017-08-02T14:15:00"
}
]

//CODE
$count = count($characters->instances);
for(reset($i); $i < $count; ++$i) {
print_r ($characters->instances[$i]->start);
}
Rich
  • 29
  • 1
  • 6
  • [This question is being discussed on meta.](https://meta.stackoverflow.com/questions/368343/how-to-deal-with-a-disputed-duplicate-flag-that-is-a-real-duplicate) – Script47 May 22 '18 at 04:55

3 Answers3

1

Instead I used 'Square Bracket' notation and echo instead of print_r which worked with strtotime, just adjusting the json_decode to true.

It worked!

Final Working Code

$characters = json_decode($data, true);

echo (date('jS  F Y h:i', strtotime($characters['instances'][$i]['start'])));
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
Rich
  • 29
  • 1
  • 6
0

First, let's convert your JSON to an array.

// The 'true' parameter will convert your
// json to an array instead of an object
$characters = json_decode($json, true);

Now, let's loop through your array to find and replace the dates.

foreach ($characters['instances'] as $instanceKey => $instance) {
    foreach ($instance as $key => $value) {
        // Add all keys you'd like to change to the below array
        if (in_array($key, ['start', 'end', 'date'])) {
            $oDate = DateTime::createFromFormat('Y-m-dTH:i:s', $value);

            // You can adjust the date format to any format you wish
            // in the below format() portion
            $characters['instances'][$instanceKey][$key] = $oDate->format('jS  F Y h:i');
        }
    }
}

Now, let's turn it back into a JSON string:

$json = json_encode($characters);

I might've guessed your JSON structure wrong. But I think this will only be a minor adjustment. For any questions, you can of course leave a comment.

halfer
  • 19,824
  • 17
  • 99
  • 186
Peter
  • 8,776
  • 6
  • 62
  • 95
-2

You can use function date() in php

print_r (date('jS  F Y h:i', strtotime("2017-08-02T14:15:00")));
FoxVSky
  • 124
  • 5