What is the correct DateTime format for MySQL Database?

前端 未结 4 1403
-上瘾入骨i
-上瘾入骨i 2020-12-21 03:57

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

String Query = \"INSERT I         


        
相关标签:
4条回答
  • 2020-12-21 04:23

    As mentioned in the comment, you are missing the delimiter , in the values. Also better to use STR_TO_DATE to convert string into date object first before inserting as:

    String Query = "INSERT INTO `restaurantdb`.`stocksdb` "+
                    " (`stock_ID`,`stock_dateUpdated`) VALUES "+
                   "('@stockID', STR_TO_DATE(@dateUpdated, '%m/%d/%Y %h:%i:%s %p'))";
    
    0 讨论(0)
  • 2020-12-21 04:32

    What I've used that works is year-month-day, with 24 hour time. In PHP it's date('Y-m-d H:i:s'), which I believe would correspond to yyyy-MM-dd HH:mm:ss in C#/.NET. (The time part is optional, and so are the dashes.)

    Confirmed in the docs, Date and Time Literals:

    Date and time values can be represented in several formats, such as quoted strings or as numbers, depending on the exact type of the value and other factors. For example, in contexts where MySQL expects a date, it interprets any of '2015-07-21', '20150721', and 20150721 as a date.

    0 讨论(0)
  • 2020-12-21 04:39

    The MySql DATETIME format is YYYY-MM-DD HH:MM:SS - See this page

    0 讨论(0)
  • 2020-12-21 04:46

    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.

    0 讨论(0)
提交回复
热议问题