So I have a table. Every entry in that table has a date associated with it, which has to:
How would you tackle this problem? I'm currently working with Postgres (but not tied to it) and leaning towards an approach that simply has an int
column for every date attribute, shifting the actual sort/compare logic into the application.
Any interesting ideas?
You can use ISO 8601 date strings. The ISO date format supports partial dates of the form you describe (but note not e.g. "April 23" without a year).
Your examples would be:
1994-05-02T12:45:00Z
2003-04
You can sort and compare these as simple strings and get the results you wanted. I.e. 2003-04-03
is lexically after 2003-04
.
You can remove any level of precision from the end and it would still work. You just can't remove components from the beginning or the middle.
Note that you need to normalize all time-zones to UTC for this to work correctly, as in the above example.
An alternate approach, if you prefer to use date/timestamp types in the database, is to store the date's precision in a secondary column. E.g. store "April 2003" as a timestamp in the date field, and use a flag in a secondary field to indicate that this date is stored with "month" precision and should not be interpreted as being "1 April 2003, 12am".
In the PG database, you store a date or a timestamp (with time zone, presumably), and rely on date arithmetics to sort them as needed.
At the app level, you turn garbage such as April 2003 into a sane format that the database will accept to store. If you're using php, strtotime helps a lot.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With