Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL date formats - difficulty Inserting a date

I am trying to further a question I asked yesterday where I wanted to know how to query a date in a different format. But now I am trying to do an insert using this method (see below) however I can't get it to work. I have checked the manual but it is not beginner friendly!

INSERT INTO custorder VALUES ('Kevin','yes'), STR_TO_DATE('1-01-2012', '%d-%m-%Y'); 
like image 948
Phil Avatar asked Mar 28 '12 12:03

Phil


People also ask

How do I insert date in YYYY-MM-DD format in MySQL?

Introduction to MySQL DATE data type This format is fixed and it is not possible to change it. For example, you may prefer to use mm-dd-yyyy format but you can't. Instead, you follow the standard date format and use the DATE_FORMAT function to format the date the way you want. MySQL uses 3 bytes to store a DATE value.

How can we enter dates in MySQL?

MySQL comes with the following data types for storing a date or a date/time value in the database: DATE - format YYYY-MM-DD. DATETIME - format: YYYY-MM-DD HH:MI:SS. TIMESTAMP - format: YYYY-MM-DD HH:MI:SS.

Which format is correct for giving a date in MySQL?

MySQL retrieves and displays DATE values in ' YYYY-MM-DD ' format. The supported range is '1000-01-01' to '9999-12-31' .

How do I automatically insert date in MySQL?

You can use now() with default auto fill and current date and time for this. Later, you can extract the date part using date() function. Let us set the default value with some date.


2 Answers

Put the date in single quotes and move the parenthesis (after the 'yes') to the end:

INSERT INTO custorder    VALUES ('Kevin', 'yes' , STR_TO_DATE('1-01-2012', '%d-%m-%Y') ) ;                         ^                                     ^ ---parenthesis removed--|                and added here ------| 

But you can always use dates without STR_TO_DATE() function, just use the (Y-m-d) '20120101' or '2012-01-01' format. Check the MySQL docs: Date and Time Literals

INSERT INTO custorder    VALUES ('Kevin', 'yes', '2012-01-01') ; 
like image 51
ypercubeᵀᴹ Avatar answered Sep 28 '22 20:09

ypercubeᵀᴹ


Looks like you've not encapsulated your string properly. Try this:

INSERT INTO custorder VALUES ('Kevin','yes'), STR_TO_DATE('1-01-2012', '%d-%m-%Y'); 

Alternatively, you can do the following but it is not recommended. Make sure that you use STR_TO-DATE it is because when you are developing web applications you have to explicitly convert String to Date which is annoying. Use first One.

INSERT INTO custorder VALUES ('Kevin','yes'), '2012-01-01';

I'm not confident that the above SQL is valid, however, and you may want to move the date part into the brackets. If you can provide the exact error you're getting, I might be able to more directly help with the issue.

like image 40
Gleeb Avatar answered Sep 28 '22 21:09

Gleeb