Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 685
mpsbhat Avatar asked Dec 18 '22 19:12

mpsbhat


2 Answers

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;
like image 133
Kevin Avatar answered Feb 12 '23 14:02

Kevin


The date_create() function accepts only the parameter link, This function is also and alias function of DateTime::__construct()

check the function date_create_from_format() its also a alias function of DateTime::createFromFormat(). Refer link

$exd = date_create_from_format('j M, Y', '01 Dec, 2015');
//$exd = date_create('01 Dec, 2015');
$exd = date_format($exd, 'Y-m-d');
echo $exd;
like image 39
Karthik N Avatar answered Feb 12 '23 15:02

Karthik N