3

My issue is that I have array how contain value with dateTime format but I would like modify this value with a format Y-m-d. I tried a lot of thing of issue here but nothing work when I encode my json.

Now I have that :

[contacts] => Array (
                    [0] => Array (
                     [createdAt] =>2020-01-29T17:00:04.159+01:00
                   )
)

And I would result like

[contacts] => Array (
                    [0] => Array (
                     [createdAt] =>2020-01-29
                   )
)

My php code is :

$contacts=$result[contacts];
foreach ($contacts as $contact) {

$time = new DateTime($contact['createdAt']);
$date = $time->format('Y-m-d');
echo '<br>' .$date; //that show the date format I want
}
//that don't show correct format
 $json=json_encode($contacts);
 print_r($json); 

Someone can help me ?

2
  • Could you please provide your code? Commented Jan 30, 2020 at 9:02
  • Yes sorry I forgot to pu my php code Commented Jan 30, 2020 at 9:06

2 Answers 2

2

You can modify you $contact array with reference &:

foreach ($contacts as &$contact) {

    $time = new DateTime($contact['createdAt']);
    $contact['createdAt'] = $time->format('Y-m-d'); 
}

Example

Sign up to request clarification or add additional context in comments.

1 Comment

That work ! thanks a lot, i didn't know we can do that
0

You can reassign value in your contact array by just doing below changes in your code

        foreach ($contacts as $key => $contact) {
            $time = new DateTime($contact['createdAt']);
            $date = $time->format('Y-m-d');
            echo '<br>' .$date; //that show the date format I want
            $contacts[$key]['createdAt'] = $date;
        }

it will reassign your new date value in your existing element

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.