user295515
user295515

Reputation: 897

How to parse a date string in PHP?

With a date string of Apr 30, 2010, how can I parse the string into 2010-04-30 using PHP?

Upvotes: 22

Views: 53814

Answers (2)

zaf
zaf

Reputation: 23244

Try strtotime() to convert to a timestamp and then date() to get it in your own format.

Upvotes: 13

Gordon
Gordon

Reputation: 316939

Either with the DateTime API (requires PHP 5.3+):

$dateTime = DateTime::createFromFormat('F d, Y', 'Apr 30, 2010');
echo $dateTime->format('Y-m-d');

or the same in procedural style (requires PHP 5.3+):

$dateTime = date_create_from_format('F d, Y', 'Apr 30, 2010');
echo date_format($dateTime, 'Y-m-d');

or classic (requires PHP4+):

$dateTime = strtotime('Apr 30, 2010');
echo date('Y-m-d', $dateTime);

Upvotes: 67

Related Questions