Store the day of the week and time?

后端 未结 4 1918
一向
一向 2020-12-09 21:26

I have a two-part question about storing days of the week and time in a database. I\'m using Rails 4.0, Ruby 2.0.0, and Postgres.

I have certain events, and those ev

4条回答
  •  醉梦人生
    2020-12-09 22:19

    Depending how complex your scheduling needs are, you might want to have a look at RFC 5545, the iCalendar scheduling data format, for ideas on how to store the data.

    If you needs are pretty simple, than that is probably overkill. Postgresql has many functions to convert date and time to whatever format you need.

    For a simple way to store relative dates and times, you could store the day of week as an integer as you suggested, and the time as a TIME datatype. If you can have multiple days of the week that are valid, you might want to use an ARRAY.

    Eg.

    • ARRAY[2,3]::INTEGER[] = Tues, Wed as Day of Week
    • '15:00:00'::TIME = 3pm

    [EDIT: Add some simple examples]

    /* Custom the time and timetz range types */
    CREATE TYPE timerange AS RANGE (subtype = time);
    
    --drop table if exists schedule;
    create table schedule (
        event_id    integer not null, /* should be an FK to "events" table */
        day_of_week integer[],
        time_of_day time,
        time_range  timerange,
        recurring   text CHECK (recurring IN ('DAILY','WEEKLY','MONTHLY','YEARLY'))
    );
    
    insert into schedule (event_id, day_of_week, time_of_day, time_range, recurring)
    values
    (1, ARRAY[1,2,3,4,5]::INTEGER[], '15:00:00'::TIME, NULL, 'WEEKLY'),
    (2, ARRAY[6,0]::INTEGER[], NULL, '(08:00:00,17:00:00]'::timerange, 'WEEKLY');
    
    select * from schedule;
    
     event_id | day_of_week | time_of_day |     time_range      | recurring 
    ----------+-------------+-------------+---------------------+-----------
            1 | {1,2,3,4,5} | 15:00:00    |                     | WEEKLY
            2 | {6,0}       |             | (08:00:00,17:00:00] | WEEKLY
    

    The first entry could be read as: the event is valid at 3pm Mon - Fri, with this schedule occurring every week.
    The second entry could be read as: the event is valid Saturday and Sunday between 8am and 5pm, occurring every week.

    The custom range type "timerange" is used to denote the lower and upper boundaries of your time range.
    The '(' means "inclusive", and the trailing ']' means "exclusive", or in other words "greater than or equal to 8am and less than 5pm".

提交回复
热议问题