1

I got two models Shift and ShiftDetail. I have a Shift model methods that adds ShiftDetails automatically:

def add_shift_details
    (0..6).each do |i|
        shift_detail = ShiftDetail.new
        t1 = Time.now

        shift_detail.weekday = i
        shift_detail.start_time = t1.beginning_of_day
        shift_detail.end_time = t1.end_of_day
        self.shift_details << shift_detail
    end
end

But when i save the instance the database is populated with

["start_time", "2016-03-02 23:00:00.000000"]
["end_time", "2016-03-03 22:59:59.999999"]

I am using Rails 4.2.5.1 and ruby 2.3.0p0

What am I doing wrong?

UPDATE:

When I test it in 'rails c', it works as expected:

2.3.0 :001 > Time.now.beginning_of_day
=> 2016-03-03 00:00:00 +0100 
2.3.0 :002 > Time.now.end_of_day
=> 2016-03-03 23:59:59 +0100
Mihai Dinculescu
  • 19,743
  • 8
  • 55
  • 70

1 Answers1

1

Your database stores DateTime in the UTC timezone while Rails works with the Berlin timezone. Berlin's midnight (GMT+1) is not equal with UTC's (GMT) midnight :)

You have two options:

  1. Have your algorithm work with an UTC timezone
    You can use Time.now.utc or DateTime.now.new_offset(0)
  2. Have your database store dates in your specific timezone (Berlin's in this case). I highly advise not to do this.

Check out this post for more information: https://stackoverflow.com/a/32229086/4304188

Community
  • 1
  • 1
Mihai Dinculescu
  • 19,743
  • 8
  • 55
  • 70