Saving 30-Feb on Mysql (Date Formating)

大城市里の小女人 提交于 2019-12-23 05:49:08

问题


I have a problem saving 'contable dates' because every month on this way has 30 days each. I need to save a element (2014-02-30) using a type date-like (not a varchar/text/blob/etc) to save this because in this project we need that. Is it possible?


回答1:


Saving such a DATE "value" in a DATE or DATETIME column is possible using the sql_mode ALLOW_INVALID_DATES and no strict mode:

ALLOW_INVALID_DATES

Do not perform full checking of dates. Check only that the month is in the range from 1 to 12 and the day is in the range from 1 to 31. This is very convenient for Web applications where you obtain year, month, and day in three different fields and you want to store exactly what the user inserted (without date validation). This mode applies to DATE and DATETIME columns. It does not apply TIMESTAMP columns, which always require a valid date.

So checking the date for an allowed contable date could be done with triggers, since there's no other check too. I assume that for this application the 31th of each month would be an invalid date.

Example:

CREATE TABLE example (
  contable_date DATE NOT NULL
) ENGINE=INNODB;

-- set the sql_mode (here for the session)
SET @@SESSION.sql_mode = 'ALLOW_INVALID_DATES';

INSERT INTO example (contable_date) VALUES ("2014-02-30");

SELECT 
    DAY(contable_date) as cday,
    MONTH(contable_date) as cmonth,
    TIMESTAMPDIFF(DAY, contable_date, '2014-03-30') as cdiff
FROM 
    example;

Result:

cday  cmonth  cdiff
-------------------
  30       2     28

Demo

Using MySQL Workbench I get with

SELECT contable_date FROM example

following result:

contable_date
-------------
   2014-02-30

but this doesn't work at sqlfiddle.com.

I wouldn't recommend this though, especially because one's not able to use strict SQL mode. One should consider the effect on the date and time functions too.



来源:https://stackoverflow.com/questions/25877242/saving-30-feb-on-mysql-date-formating

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!