user1857116 user1857116 - 14 days ago 5
PHP Question

PHP DateTime Object convert from format A to format B

I have the string

'19720505'
(year + month with leading zero + day with leading zero).
How to convert it to the format
Y-m-d 00:00:00
using the PHP DateTime class?

Answer

First convert your yyyymmdd to a DateTime object:

$inputString = "19720505";

$date = DateTime::createFromFormat("Ymd", $inputString);

Then convert your DateTime object to string in desired format:

$outputString = $date->format('Y-m-d H:i:s');

All this operations are considered basic and very simple. You should read PHP Documentation before asking something so basic here.

http://php.net/manual/en/class.datetime.php

Comments