Pierre Dommerc Pierre Dommerc - 9 days ago 6
PHP Question

Format a date given from a json

I search a way to format a date given from a json response. Currently I can pass the date via json response into both format :

the string format:

{"date":"2016-11-25T11:24:54+0100"}


or the object format:

"date":{"timezone":{"name":"Europe\/Paris","location":{"country_code":"FR","latitude":48.86666,"longitude":2.33333,"comments":""}},"offset":3600,"timestamp":1480069808}}


I have to format one of this two json formats into that format:
dd/mm/aaaa
, example: 25/11/2016

This operation must be done in my view, with jQuery/js, or in the controller before send the json reponse:

/* $normalizer = new GetSetMethodNormalizer(); here the code for fomat the date into string
$callback = function ($dateTime) {
return $dateTime instanceof \DateTime
? $dateTime->format(\DateTime::ISO8601)
: '';
};
$normalizer->setCallbacks(array('date' => $callback));*/

$normalizer->setIgnoredAttributes(array('article'));
$serializer = new Serializer(array($normalizer), array($encoder));
$dataJSON = $serializer->serialize($data, 'json');

$response = new Response();
$response->setContent($dataJSON);
$response->headers->set('Content-Type', 'application/json');

return $response;

Answer

use PHPs build in DateTime class like

<?php

$date = new Datetime('2016-11-25T11:24:54+0100');
var_dump($date->format('d.m.Y h:i:s')); // string(19) "25.11.2016 11:24:54"
Comments