62

I have a date field in php which is using this code:

$date = mysql_real_escape_string($_POST['intake_date']);

How do I convert this to MySql format 0000-00-00 for inclusion in db. Is it along the lines of: date('Y-m-d' strtotime($date);. The reason I ask, is because I have tried variations of this and I cannot seem to get it to work. Either displays as 1970 or some other variation of that. Many thanks

3
  • 7
    How is $_POST['intake_date'] currently formatted? I suppose the MySQL column has type DATE? Commented Jul 22, 2011 at 13:47
  • is the orignal date a unix timestamp? (139293929 looking thing) Commented Jul 22, 2011 at 13:48
  • @jakub no, it is 0000-00-00 00:00:00 Commented Jul 22, 2011 at 13:50

9 Answers 9

156
$date = mysql_real_escape_string($_POST['intake_date']);

1. If your MySQL column is DATE type:

$date = date('Y-m-d', strtotime(str_replace('-', '/', $date)));

2. If your MySQL column is DATETIME type:

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

You haven't got to work strototime(), because it will not work with dash - separators, it will try to do a subtraction.


Update, the way your date is formatted you can't use strtotime(), use this code instead:

$date = '02/07/2009 00:07:00';
$date = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '$3-$2-$1 $4', $date);
echo $date;

Output:

2009-07-02 00:07:00
Sign up to request clarification or add additional context in comments.

9 Comments

@bollo: Have you tried my code, yet? Give me a sample datetime to test, but I suspect it will work just fine.
it is still reversing the d & m. for example, using your code, after conversion, this is what appears in db: 2009-02-07 00:07:00 but it should be 2009-07-02 00:07:00. The response in firbug is showing the post as 02/07/2009 00:07:00. THANKS
@bollo: The way your date is formatted, it is not possible to use strtotime(). I updated my answer. Please check the code on the update part.
I am not up much on preg_replace. What exactly is code doing? also, how is my date formatted differently? I am using this format on other pages with no probs. As a test, i sent the response back through firebug json and this is the result: "date": "2009-02-07 00:07:00", so it isn,t reaching the db correctly. Thanks
@bollo: The way you have your date right now, it is DD/MM/YYYY, it should be MM/DD/YYYY to work with strtotime(). The preg_replace() above will format the date to the output style I am showing above. Maybe you sent back the wrong variable, because I just double checked it, and it is responding with the way you want the date formatted.
|
17

This site has two pretty simple solutions - just check the code, I provided the descriptions in case you wanted them - saves you some clicks.

http://www.richardlord.net/blog/dates-in-php-and-mysql

1.One common solution is to store the dates in DATETIME fields and use PHPs date() and strtotime() functions to convert between PHP timestamps and MySQL DATETIMEs. The methods would be used as follows -

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

2.Our second option is to let MySQL do the work. MySQL has functions we can use to convert the data at the point where we access the database. UNIX_TIMESTAMP will convert from DATETIME to PHP timestamp and FROM_UNIXTIME will convert from PHP timestamp to DATETIME. The methods are used within the SQL query. So we insert and update dates using queries like this -

$query = "UPDATE table SET
    datetimefield = FROM_UNIXTIME($phpdate)
    WHERE...";
$query = "SELECT UNIX_TIMESTAMP(datetimefield)
    FROM table WHERE...";

2 Comments

I using this code: $date = mysql_real_escape_string($_POST['intake_date']); $newdate = date('Y-m-d H:i:s', strtotime($date)); but it seems to be putting it in YYYY-dd-mm in 00:00:00 in the db. the day and month seem to be reversed. thanks
I'm not entirely sure why that would happen to be honest - I'll think about it and get back to you unless someone beats me to it - sorry about that!
6

Where you have a posted date in format dd/mm/yyyy, use the below:

$date = explode('/', $_POST['posted_date']);
$new_date = $date[2].'-'.$date[1].'-'.$date[0];

If you have it in mm/dd/yyyy, just change the second line:

$new_date = $date[2].'-'.$date[0].'-'.$date[1];

Comments

5

You are looking for the the MySQL functions FROM_UNIXTIME() and UNIX_TIMESTAMP().

Use them in your SQL, e.g.:

mysql> SELECT UNIX_TIMESTAMP(NOW());
+-----------------------+
| UNIX_TIMESTAMP(NOW()) |
+-----------------------+
|            1311343579 |
+-----------------------+
1 row in set (0.00 sec)

mysql> SELECT FROM_UNIXTIME(1311343579);
+---------------------------+
| FROM_UNIXTIME(1311343579) |
+---------------------------+
| 2011-07-22 15:06:19       |
+---------------------------+
1 row in set (0.00 sec)

Comments

5

If intake_date is some common date format you can use date() and strtotime()

$mysqlDate = date('Y-m-d H:i:s', strtotime($_POST['intake_date']));

However, this will only work if the date format is accepted by strtotime(). See it's doc page for supported formats.

Comments

3

PHP 5.3 has functions to create and reformat at DateTime object from whatever format you specify:

$mysql_date = "2012-01-02";   // date in Y-m-d format as MySQL stores it
$date_obj = date_create_from_format('Y-m-d',$mysql_date);
$date = date_format($date_obj, 'm/d/Y');
echo $date;

Outputs:

01/02/2012

MySQL can also control the formatting by using the STR_TO_DATE() function when inserting/updating, and the DATE_FORMAT() when querying.

$php_date = "01/02/2012";
$update_query = "UPDATE `appointments` SET `start_time` = STR_TO_DATE('" . $php_date . "', '%m/%d/%Y')";
$query = "SELECT DATE_FORMAT(`start_time`,'%m/%d/%Y') AS `start_time` FROM `appointments`";

Comments

2
function my_date_parse($date)
{
        if (!preg_match('/^(\d+)\.(\d+)\.(\d+)$/', $date, $m))
                return false;

        $day = $m[1];
        $month = $m[2];
        $year = $m[3];

        if (!checkdate($month, $day, $year))
                return false;

        return "$year-$month-$day";
}

Comments

1

There is several options.

Either convert it to timestamp and use as instructed in other posts with strtotime() or use MySQL’s date parsing option

Comments

1

If you know the format of date in $_POST[intake_date] you can use explode to get year , month and time and then concatenate to form a valid mySql date. for example if you are getting something like 12/15/1988 in date you can do like this

    $date = explode($_POST['intake_date'], '/');
    mysql_date = $date[2].'-'$date[1].'-'$date[0];

though if you have valid date date('y-m-d', strtotime($date)); should also work

Comments

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.