Search code examples
mysqlsqldatetimestampvarchar

Can't store dates from input value


UPDATE blogs SET start_date = '11/27/2012 00:00',end_date = '11/27/2012 00:00' WHERE id='9'

This query won't store start_date or end_date values for blog id 9 unless I set them to varchar type.

Tried with timestamp and date time but the query allways will return that 0 rows where affected

the thing is I need to be able to check for rows in a interval of time, and with varchar it makes very complicated.

What am i missing?


Solution

  • As stated in Date and Time Literals:

    MySQL recognizes DATETIME and TIMESTAMP values in these formats:

    • As a string in either 'YYYY-MM-DD HH:MM:SS' or 'YY-MM-DD HH:MM:SS' format. A “relaxed” syntax is permitted here, too: Any punctuation character may be used as the delimiter between date parts or time parts. For example, '2012-12-31 11:30:45', '2012^12^31 11+30+45', '2012/12/31 11*30*45', and '2012@12@31 11^30^45' are equivalent.

    • As a string with no delimiters in either 'YYYYMMDDHHMMSS' or 'YYMMDDHHMMSS' format, provided that the string makes sense as a date. For example, '20070523091528' and '070523091528' are interpreted as '2007-05-23 09:15:28', but '071122129015' is illegal (it has a nonsensical minute part) and becomes '0000-00-00 00:00:00'.

    • As a number in either YYYYMMDDHHMMSS or YYMMDDHHMMSS format, provided that the number makes sense as a date. For example, 19830905132800 and 830905132800 are interpreted as '1983-09-05 13:28:00'.

    Therefore, the strings '11/27/2012 00:00' and '11/27/2012 00:00' are not valid MySQL datetime literals. You have two options (in some vague order of preference, without any further information of your requirements):

    1. Provide your literals in a recognised format:

      UPDATE blogs SET
        start_date = '2012-11-27 00:00:00',
        end_date   = '2012-11-27 00:00:00'
      WHERE id = 9
      
    2. Use MySQL's STR_TO_DATE() function to convert the string:

      UPDATE blogs SET
        start_date = STR_TO_DATE('11/27/2012 00:00', '%m/%d/%Y %H:%i'),
        end_date   = STR_TO_DATE('11/27/2012 00:00', '%m/%d/%Y %H:%i')
      WHERE id = 9