Search code examples
phpdate-format

PHP date_format(): How to format date from string value


I have a bit of PHP code:

$exd = date_create('01 Dec, 2015');
$exd = date_format($exd, 'Y-m-d');
echo $exd;

Which is used for formatting the date. The expected output would be 2015-12-01 but it returns 2016-12-01. What am i missing?


Solution

  • Use createFromFormat method first, provide the input format:

    $exd = DateTime::createFromFormat('d M, Y', '01 Dec, 2015');
    // arguments (<format of the input>, <the input itself>)
    $exd = date_format($exd, 'Y-m-d'); // then choose whatever format you like
    echo $exd;