Storing day and month (without year)

前端 未结 3 748
离开以前
离开以前 2020-12-13 04:52

I\'m having trouble with figuring out the best way to store some data in my database. I\'ve got to store DD/MM dates in a database, but I\'m not sure of the best way to stor

3条回答
  •  半阙折子戏
    2020-12-13 05:14

    I've got to store DD/MM dates in a database, but I'm not sure of the best way to store this so that it can be easily sorted and searched.

    The best way to store date data, even if the year component is not required, is to use date. When you need to use it, you can remove the year, or replace it with the year being compared against (or current year).

    Having it in date column facilitates sorting correctly, integrity, validation etc.

    To cater for leap years, use a year like '0004' which allows '0004-02-29'. Using year 4 makes it slightly more complicated than year 0, but as an example, this turns the date '29-Feb' (year agnostic) into a date in this year for comparison with some other field

    select
        affffdate(
        subdate(cast('0004-02-29' as date),
            interval 4 year),
            interval year(curdate()) year)
    
    result: 2011-02-28
    

提交回复
热议问题