jack
jack

Reputation:

how to store a date in a mysql database?

If I have a date such as mm/dd/yyyy. How can I get mysql to actually store the date in that format. Is this possible or do have to store it in the form of yyyy/mm/dd and convert it later?

What I want to do is insert a date in the mm/dd/yyyy format but the database will not allow it. It wants yyyy/mm/dd

Upvotes: 3

Views: 11825

Answers (4)

Josef Sábl
Josef Sábl

Reputation: 7762

What is your reason for doing this? I can't see any reasonable use for it.

You cannot change the way MySQL stores dates, no. But you can of course format them when reading/writing them. You can do it in SQL query like this:

For example you can use STR_TO_DATE function to format the date when inserting it:

INSERT INTO mytable (mydate) VALUES (STR_TO_DATE('12/31/2009', '%m/%d/%Y'))

And vice versa:

SELECT DATE_FORMAT(mydate, '%m/%d/%Y') FROM mytable /* returns 12/31/2009 */

But as FactalizeR pointed out, it is not a good practice to do it in the query and it should be moved to script, like this (considering you are using PHP).

$date = '12/31/2009';
$date = date('Y-m-d', strtotime($date));
mysql_query("INSERT INTO mytable (mydate) VALUES ({$date})");

And vice versa

$date = mysql_result(mysql_query("SELECT mydate FROM mytable"), 0, 0);
$date = date('m/d/Y', strtotime($date)); //returns 12/31/2009

Upvotes: 8

Unsliced
Unsliced

Reputation: 10552

I think you're mixing up what you are storing - the date itself - with how that date is subsequently referred to.

Why do you want to store in a particular format? Do you want to insert in that format? In which case you might be able to get away with it, depending on the localisation of your install, but otherwise convert - insert would be the way to do it (depending, of course, on how you're inserting).

Are you creating a SQL command from strings?

Upvotes: 1

Evernoob
Evernoob

Reputation: 5561

MySQL DATE fields must store the date in YYYY-MM-DD (including dashes) format. If you attempt to store it any other way you will have problems with date comparisons and ordering.

Conversion later is a trivial task. Is there a compelling reason why you are trying to avoid doing this? What other technology are you using to talk to the MySQL database? (i.e. PHP, C# etc...)

Upvotes: 1

Vladislav Rastrusny
Vladislav Rastrusny

Reputation: 30013

There is a built-in DATE type in MySQL. It allows to store a date. And later in your programming language you extract this date and convert to whatever format you like. Also, conversion can be done directly in MySQL via DATE_FORMAT(date,format) function.

Upvotes: 1

Related Questions