5

My $date output is in the foreach loop

09/25/11, 02/13/11, 09/15/10, 06/11/10, 04/13/10, 04/13/10, 04/13/10, 09/24/09, 02/19/09, 12/21/08

My mysql query(PHP) is as follows

("INSERT INTO table_name(`field1`, `field2`,`date`) VALUES ('".$value1."','".$value2 ."','".$date."')");

Question: In my database all the dates stores as 0000-00-00 00:00:00. But 4th date (06/11/10) is stored as 2006-11-10 00:00:00.

I tried with date('Y-m-d H:i:s', $date); but no help.

Note: My database field is datetime type. Any idea?

Saturnix
  • 10,130
  • 17
  • 64
  • 120
vidhyakrishnan
  • 83
  • 1
  • 1
  • 6
  • 1
    You should format the `date` according to spec: http://dev.mysql.com/doc/refman/5.1/en/datetime.html or use `STR_TO_DATE()`. This might help you: http://stackoverflow.com/a/12120457/1057429 – Nir Alfasi Jun 12 '13 at 23:35

3 Answers3

13

You're on the right track with your date('Y-m-d H:i:s',$date); solution, but the date() function takes a timestamp as its second argument, not a date.

I'm assuming your examples are in American date format, as they look that way. You can do this, and it should get you the values you're looking for:

date('Y-m-d H:i:s', strtotime($date));

The reason it's not working is because it expects the date in the YYYY-MM-DD format, and tries to evaluate your data as that. But you have MM/DD/YY, which confuses it. The 06/11/10 example is the only one that can be interpreted as a valid YYYY-MM-DD date out of your examples, but PHP thinks you mean 06 as the year, 11 as the month, and 10 as the day.

Joel Hinz
  • 24,719
  • 6
  • 62
  • 75
1

I created my own function for this purpose, may be helpful to you:

function getTimeForMysql($fromDate, $format = "d.m.y", $hms = null){
    if (!is_string($fromDate))  
        return null ;       
    try {
        $DT = DateTime::createFromFormat($format, trim($fromDate)) ;
    } catch (Exception $e) { return null ;}

    if ($DT instanceof DateTime){
        if (is_array($hms) && count($hms)===3)
             $DT->setTime($hms[0],$hms[1],$hms[2]) ;
        return ($MySqlTime = $DT->format("Y-m-d H:i:s")) ? $MySqlTime : null ;
    }
    return null ;
}

So in your case, you use format m/d/yy :

$sql_date = getTimeForMysql($date, "m/d/yy") ;
if ($sql_date){
  //Ok, proceed your date is correct, string is returned.
}
sybear
  • 7,837
  • 1
  • 22
  • 38
0

You don't have the century in your date, try to convert it like this:

<?php
$date = '09/25/11';
$date = DateTime::createFromFormat('m/d/y', $date);
$date = $date->format('Y-m-d');
print $date;

Prints:

2011-09-25

Now you can insert $date into MySQL.

user4035
  • 22,508
  • 11
  • 59
  • 94