2

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"
}
6
  • date is coming through your json code?? Commented Feb 16, 2017 at 10:56
  • Sorry, I forgot. JSON looks like: { "date" : "2017-02-15 15:20:14" } Commented Feb 16, 2017 at 10:58
  • that is coming right then directly you will access what is the problem?? Commented Feb 16, 2017 at 10:59
  • Sorry i´m new. I want to add the date into my database with Doctrine. Commented Feb 16, 2017 at 11:00
  • 1
    so decode the json response and get the date and store in database... Commented Feb 16, 2017 at 11:02

2 Answers 2

3

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

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

1 Comment

important to know: if $content['date'] is null for any reason or not in a correct format, DateTime() will most probably provide you with an unexpected date (e.g. for null it's now).
3

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']);

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.