Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

c# - What is the correct DateTime format for MySQL Database?

I am Inserting this DateTime data '12/21/2012 1:13:58 PM' into my MySQL Database using this SQL string:

String Query = "INSERT INTO `restaurantdb`.`stocksdb` 
                  (`stock_ID`,`stock_dateUpdated`) 
                  VALUES ('@stockID' '@dateUpdated');

and I receive this error message:

Incorrect datetime value: '12/21/2012 1:13:58 PM' for column 'stock_dateUpdated' at row 1

So what is the right format/value for dateTime to input into a MySQL database?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Q: What is the right format/value for DATETIME literal within a MySQL statement?

A: In MySQL, the standard format for a DATETIME literal is:

 'YYYY-MM-DD HH:MI:SS'

with the time component as a 24 hour clock (i.e., the hours digits provided as a value between 00 and 23).

MySQL provides a builtin function STR_TO_DATE which can convert strings in various formats to DATE or DATETIME datatypes.

So, as an alternative, you can also specify the value of a DATETIME with a call to that function, like this:

STR_TO_DATE('12/21/2012 1:13:58 PM','%m/%d/%Y %h:%i:%s %p')

So, you could have MySQL do the conversion for you in the INSERT statement, if your VALUES list looked like this:

... VALUES ('@stockID', STR_TO_DATE('@dateUpdated','%m/%d/%Y %h:%i:%s %p');

(I notice you have a required comma missing between the two literals in your VALUES list.)


MySQL does allow some latitude in the delimiters between the parts of the DATETIME literal, so they are not strictly required.

MySQL 5.5 Reference Manual.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...