Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to store a date without a year in SQL database?

I am building an app that has a daily quote that should be stored in the database. Each quote is assigned with a day of the year, including one for Feb 29th. Since the quote only cares about the day not the year should I still use smalldatetime type? Please let me know your opinions, thanks!!

like image 777
Mike Avatar asked Apr 20 '10 12:04

Mike


People also ask

How do I isolate a year from a date in SQL?

You can extract the year using the extract() function in standard SQL. The function takes date or DateTime objects and returns the year as a string.

What is the best way to save date in database?

The default way to store a date in a MySQL database is by using DATE. The proper format of a DATE is: YYYY-MM-DD. If you try to enter a date in a format other than the Year-Month-Day format, it might work but it won't be storing the dates as you expect.


2 Answers

If you need to retain the day and month data, you might as well use SmallDateTime and simply ignore the year component (or set it to the same value across the board, for example 2000 which was a leap year, so leap dates will be allowed).

You still get to use proper date and time functions with the correct data type and if you go with a VARCHAR field you will end up converting to and from it.

like image 51
Oded Avatar answered Oct 07 '22 23:10

Oded


I can't help feeling that if the calendar had been invented by a software engineer that the leap day would be the 32nd of December rather than the 29th of Feb. That way you could simply use a smallint offset from the 1st Jan.

You can still use a smallint offset from the 1st of March, with 1st March as 0, 2nd March as 1, 29th Feb as 365. However it involves doing some kind of custom conversion to the figure you want and may not sort as you would like to.

Given that you can store the Day and Month as two tinyints taking up the same space, I'm not sure this would be a good plan, but thought I would mention it for completeness.

like image 44
Martin Brown Avatar answered Oct 08 '22 00:10

Martin Brown