Rejoanul Alam
Rejoanul Alam

Reputation: 5398

Format the formatted date for mysql

How can I format this date 01 August, 15 for mysql DATE field. So I need this 2015-08-01 format from 01 August, 15 this format in PHP. Tried following but not work

echo date('Y-m-d',strtotime('01 August, 15'));

Upvotes: 1

Views: 122

Answers (2)

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13263

It is because strtotime() does not understand what 01 August, 15 means. Try it:

var_dump(strtotime('01 August, 15')); // false

The 15 at the end is too ambiguous; it could be the day of the month or a short year.

The easiest way to make this work is probably to use DateTime::createFromFormat, like so:

$date   = '01 August, 15';
$parsed = DateTime::createFromFormat('d F, y', $date);
echo $parsed->format('Y-m-d');

If you control the format of the date then you could also make it easier to parse. Formatting it like 01 August 2015 would work, for example.

Upvotes: 2

Jantje
Jantje

Reputation: 83

First remove the , out of the date and then use the strtotime function. So:

$date = "01 August, 15";
$date = str_replace(",", "", $date);
echo date("Y-m-d",strtotime($date));

Upvotes: 1

Related Questions