1

I need to convert a date in this format:

November 28, 2009

to a MySQL date format:

2009-28-11

What's the best method to convert the date using PHP?

4 Answers 4

10

Improvised from: http://www.bigroom.co.uk/blog/dates-in-php-and-mysql

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

// Example:
$phpdate = 'November 20, 2009';
$mysqldate = date( 'Y-m-d', strtotime( $phpdate ) );

echo $mysqldate;
// output: 2009-11-20
Sign up to request clarification or add additional context in comments.

1 Comment

Darn - beat me by just a few seconds. Good answer. ;)
5

If you want a "date" to be converted to "DateTime" this is the best way =

// for example: you have a string with the following
$dateFormat = 'd/m/Y';
$dateString = '02/12/2019';

// you can easily create DateTime using
$dateTime = \DateTime::createFromFormat($dateFormat, $dateString);

As described in the php documentation for createFromFormat.

And to answer completely on your question:

echo $dateTime->format('y-m-d');

Comments

4

I like to use strtotime and the date function as follows:

$mysql_date = date("Y-m-d", strtotime($source_date));

Comments

1

There are two options you can use which are strtotime or preg_split and sprintf. I recommend you use strtotime. The structure goes like this:

$date = 'November 28 2009';
$sqldate = date('Y-m-d', strtotime($date));

Make sure the Y is capital so it reads as 0000 otherwise it will read 00.

1 Comment

What do you mean with preg_split and sprintf? Can you give an example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.