Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails. How to store time of day (for schedule)?

I'm writing an app that keeps track of school classes.

I need to store the schedule. For example: Monday-Friday from 8:am-11am.

I was thinking about using a simple string column but I'm going to need to make time calculations later.

For example, I need to store a representation of 8am, such as start_at:8am end_at:11am

So how should I store the time? What datatype should I use? Should I store start time and number of seconds or minutes and then calculate from there? or is there an easier way?

I use MySQL for production and SQLite for development.

like image 656
leonel Avatar asked Aug 15 '12 16:08

leonel


Video Answer


2 Answers

I made an app recently that had to tackle this problem. I decided to store open_at and closed_at in seconds from midnight in a simple business hour model. ActiveSupport includes this handy helper for finding out the time in seconds since midnight:

Time.now.seconds_since_midnight 

This way I can do a simple query to find out if a venue is open:

BusinessHour.where("open_at > ? and close_at < ?", Time.now.seconds_since_midnight, Time.now.seconds_since_midnight) 

Any tips for making this better would be appreciated =)

like image 108
chourobin Avatar answered Oct 03 '22 03:10

chourobin


If you're using Postgresql you can use a time column type which is just the time of day and no date. You can then query

Event.where("start_time > '10:00:00' and end_time < '12:00:00'") 

Maybe MySQL has something similar

like image 20
idrinkpabst Avatar answered Oct 03 '22 03:10

idrinkpabst