Kevin Liss
Kevin Liss

Reputation: 136

JSON Array to PHP DateTime

How do I get PHP Date Time from a JSON?

$params = array();
 $content = json_decode($request->getContent(), true);
 if(empty($content))
{
   throw $this->createNotFoundException('JSON not send!')
}

$content['date'] need to be smomething like $date = new DateTime();

JSON looks like :

{
    "date" : "2017-02-15 15:20:14"
}

Upvotes: 2

Views: 15379

Answers (2)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

I assume that echo "<pre/>";print_r($content); is given data like below:-

Array
(
    [date] => 2017-02-15 15:20:14
)

So do like below:-

echo date ('Y-m-d H:i:s',strtotime($content['date'])); // normal date conversion

echo PHP_EOL;

$dateTime = new DateTime($content['date']); // datetime object

echo $dateTime->format('y-m-d H:i:s');

Output:-https://eval.in/738434

Upvotes: 3

DRCSH
DRCSH

Reputation: 29

The date you're getting from JSON is coming in as a string, so you'll need to build a DateTime object from that string. As long as the string is in a format recognised by PHP's date and time formats (http://php.net/manual/en/datetime.formats.php) you can do it very simply as follows:

$date = new DateTime($content['date']);

Upvotes: 3

Related Questions