MySQL date formats - difficulty Inserting a date

Phil picture Phil · Mar 28, 2012 · Viewed 274.8k times · Source

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

Answer

ypercubeᵀᴹ picture ypercubeᵀᴹ · Mar 28, 2012

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