Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert this date to Y-m-d (PHP)?

Tags:

date

php

I have this date as a string: 10.21.2011, the format is mm.dd.yyyy

How can I convert this to Y-m-d? This is what I tried, but it always gives me the 1970 date.

$date = date('Y-m-d', strtotime($date));

Thanks!

like image 830
EOB Avatar asked Dec 04 '22 16:12

EOB


2 Answers

The object-oriented way:

$date = DateTime::createFromFormat('m.j.Y', '10.21.2011');
echo $date->format('Y-m-d');

My opinion is that this is the approach one should try to learn with PHP.

Requires PHP 5.3.

like image 125
eis Avatar answered Dec 07 '22 23:12

eis


Most likely because of period .:

$date = '10.21.2011';
echo date('Y-m-d', strtotime(str_replace('.', '/', $date)));

Result:

2011-10-21
like image 29
Sarfraz Avatar answered Dec 07 '22 22:12

Sarfraz