I would like to know how to handle and store dates like birthdates in Ruby on Rails when the exact day or month might be unknown and some birthdates are BC.
MySQL seems to support dates like "1990-00-00", which could be used to store the year without month and day, but BC dates don't seem to be possible. Since MySQL supports dates until the year 9999 and I need only birthdates up to today, the higher dates could be used to represent BC dates (9999 = -1, 9998 = -2, ...), but this seems complicated and messy.
CodePudding user response:
Switch to Postgresql? LOL, just kidding. There are some solutions out there that suggest adding a constant to ALL dates in the background then subtracting it before display. Seems messy. Rails doesn't care how long ago your date is though. So you could store those dates as strings like '2023-01-29' or '-5000-01-29' and then parse them in rails:
Date.parse('29 Jan 2023')
=> Sun, 29 Jan 2023
Date.parse('-5000-01-29')
=> Fri, 29 Jan -5000
Date.parse('29 Sep 1000 BC')
=> Sun, 29 Sep -0999
As you can see Rails handles dates quite well and can parse a number of different string formats into dates. You could override the setter/getter for the column in the model:
class Foo < ActiveRecord::Base
# "Uses a string to hold the date for the column 'bar'"
def bar=(date)
super(date.to_s)
end
def bar
Date.parse(super)
end
end
Now when you have an instance of Foo and call .bar
it will get converted from the string in the DB to a date, and when given a date in the setter method it will convert it to a string for you.