0

I have a date ("mm/dd/yyyy") and I want to convert it to a MySQL DATE data type (like yyyy-mm-dd)

How do I do it with PHP?

6 Answers 6

7

Take a look at mysql function str_to_date()

example

select str_to_date('10/30/2010','%m/%d/%Y') -- 2010-10-30
Sign up to request clarification or add additional context in comments.

1 Comment

I nead something like a regex
5

Nick rulez's answer also applies to inserts and updates:

INSERT INTO my_table (id, date) values (1, str_to_date('10/30/2010','%m/%d/%Y'))

Comments

2

Lots of ways to do it. I like always converting my dates to a timestamp cause I find it easiest to then do what I want.

In which case:

<?php
echo date( "Y-m-d",strtotime("09/02/1988"));
?>

http://codepad.viper-7.com/Z9vDv7

1 Comment

What about 03/04/2011? Is that April 3rd or March 4th? strtotime is handy but it's NOT a magic bullet. Safer to use date_create_from_format() when you know what the format is in advance.
1

If your date is in $your_date, then:

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

See strtotime() documentation.

2 Comments

To MySQL, it's still only a string that you hope is interpreted as a DATE data type.
@OMG_Ponies How do you think MySQL processes DATE type? This is actually more a string than real time format (like TIMESTAMP where the value is stored in a Unix epoch).
0
$date = '12/25/2011';
$parts = explode('/', $date);
$sql_date = $parts[2] . '-' . $parts[0] . '-' . $parts[1];

4 Comments

What about '01/02/2011' - is that Feb 1st, or Jan 2nd? Not everyone's date format is the same...
My point was, regardless of what the OP says, this solution is not ideal for most situations.
Of course not. If you have a date 01/02/2011 and you have no idea what each field represents, then there's nothing that can help.
@OMG it must be the same as it is grabbed from facebook's connect api using the PHP SDK 3, it's the birthday of the user.
0
function date2mysql($date) {

   list($month, $day, $year) = explode('/', $date);
   $timestamp = mktime(0, 0, 0, $month, $day, $year);
   return date("Y-mm-d",$timestamp);
}

see the date manual for the format

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.