I am using Xata as my database and it has a datetime column type which I am using at the moment for the opening hours of a restaurant. But it is not always convenient when I use it only for the hours and minutes. This gives problems when sorting because I always have to extract the time from the date and I also have time zone issues I have to deal with. What is the best practice in this situation? Continue using the datetime data type or switch to string? I am displaying the opening hours in the following format "hh:mm" for each day.
Question posted in Javascript
A very good W3school tutorial can be found here.
A very good W3school tutorial can be found here.
3
Answers
You probably don’t want to use
datetime
for this use-case, because it represents a time on a specific day, whereas your opening times are recurring every week.If your database has a
time
type, it’s more appropriate. If not, use a number (minutes since midnight) or (or string) + a separate field for the timezone. The time you store should be local to the restaurant, not translated to UTC. This is because you don’t want the opening times to shift by an hour by the time DST comes around.An extra thing you may run into in the future is that some places will have a closing time past midnight, but from an ‘opening times’ and accounting perspective it’s usually counted as the day before. So does
5:00
mean 5am the current day, or the next? So the simplest may be to store the opening time + how long the restaurant is open for to avoid this problem.Taking a look at the Xata docs, it seems there’s no
time
type, so my vote would go for a table withday_of_the_week
, andopening_time
andopening_duration
typed asint
expressed as minutes since midnight and minutes since opening respectively.Source: I’m a former member of the CalConnect internet calendaring standards group.
Never store temporal data as strings.
Use appropriate date/time data types – including
date
,time
,timestamp
,timestamptz
, andinterval
. Or maybe a range type based on one of these.Which are appropriate depends on the full (undisclosed) use case.
If your opening hours never cross midnight,
time
may be fine. Else,timestamp
may be best.Related:
Always a nice "problem" and one that is easy to solve: Just store every day that your property is open. With just 365 days a year, you can only create 11000 records for the next 30 years. With 10.000 restaurants, it would take just 110 million records. This is why databases were invented in the first place!
Something like this works like a charm and could easily convert into a reservation system, including constraints to avoid double reservations.
With this you will never have problems with exceptions, every day you can set something different. You can delete a date, later on open that day again, change the time, etc. And searching is easy, just use the standard timestamp and tsrange functions.