med
med

Reputation: 469

mysql date formatting with php

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?

Upvotes: 0

Views: 215

Answers (6)

Sebastián Grignoli
Sebastián Grignoli

Reputation: 33462

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'))

Upvotes: 5

chriscatfr
chriscatfr

Reputation: 2662

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

Upvotes: 0

Layke
Layke

Reputation: 53206

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

Upvotes: 2

Tadeck
Tadeck

Reputation: 137440

If your date is in $your_date, then:

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

See strtotime() documentation.

Upvotes: 1

rid
rid

Reputation: 63580

$date = '12/25/2011';
$parts = explode('/', $date);
$sql_date = $parts[2] . '-' . $parts[0] . '-' . $parts[1];

Upvotes: 0

Nicola Cossu
Nicola Cossu

Reputation: 56397

Take a look at mysql function str_to_date()

example

select str_to_date('10/30/2010','%m/%d/%Y') -- 2010-10-30

Upvotes: 7

Related Questions