Alfredo Rafael
Alfredo Rafael

Reputation: 27

Why I get a wrong time if a set the correct time zone in rails?

I am trying to save opening and closing hours of a branch as time in ruby ​​on rails, but it is saved with a difference of -6 hours when I need it to be -5 as it is the local time

In the other models I save date and time as datetime and the correct time is saved, but at the branch I only need time

In my application.rb

config.time_zone = 'Monterrey' // It has -5 difference

In my schema

  create_table "branches", force: :cascade do |t|
    t.string "name"
    t.string "address"
    t.time "open_time"
    t.time "close_time"
  end

// In bookings work correctly

 create_table "bookings", force: :cascade do |t|
    t.string "client_name"
    t.datetime "date"
  end

Example

If I save a Booking, has the correct time zone

> Booking.last.date
=> Sun, 12 Apr 2020 17:31:00 CDT -05:00

But if I save a branch, has a wrong time zone

> Branch.last.open_time
=> Fri, 31 Dec 1999 22:50:00 CST -06:00 

Upvotes: 3

Views: 1491

Answers (1)

UrsaDK
UrsaDK

Reputation: 865

When showing a timestamp ruby will tell you both the name of the time zone (ie: CDT, CST), and the offset from UTC (ie: -05:00, -06:00). The two time zones you're seeing are:

  • Central Daylight Time:

    > Booking.last.date
    => Sun, 12 Apr 2020 17:31:00 CDT -05:00
    
  • Central Standard Time:

    > Branch.last.open_time
    => Fri, 31 Dec 1999 22:50:00 CST -06:00 
    

Accounting for the daylight saving hours is the only difference between these time zones.

Geographically, both time zones represent the same area, where CST is used during the winter months, and CDT - during the summer months.

Upvotes: 2

Related Questions