Reputation: 19969
I have a class method like this:
def self.seed
InventoryPeriod.delete_all
(1..8).each do |i|
self.create! name: "name#{i}", start_datetime: DateTime.new(2014,i,1), end_datetime:DateTime.new(2014,i,-1), location_id: 12
end
end
but it seems like it should be writing to the database in UTC (DateTime.new(2014,i,1).utc
doesn't do it) but it doesn't and basically is off by 8 hours.
For example:
| 51 | 2014-08-01 00:00:00 | 2014-08-31 00:00:00
but should be:
| 51 | 2014-07-31 16:00:00 | 2014-08-30 16:00:00
What's the best solution for this? Hopefully, some rails thing that I'm not aware of - would seem like there should be since it must be so common. Or do I manually adjust by the necessary hours?
Upvotes: 3
Views: 317
Reputation: 6918
If your attributes are time zone aware and you desire to skip time zone conversion for certain attributes then you can do following:
Model_Name.skip_time_zone_conversion_for_attributes = [:attribute_name]
OR Generally you can call this inside the model:
skip_time_zone_conversion_for_attributes
Ref: http://api.rubyonrails.org/v3.0.0/classes/ActiveRecord/Timestamp.html
For this to work, please make sure you have not specified any specific Time Zone in application.rb
file.
Or if you want a fixed Timezone other than UTC:
Please refer How to change default timezone for Active Record in Rails?
Hope it helps :)
Upvotes: 2
Reputation: 7070
The problem is that when you're doing DateTime.new(y,m,d)
, the time zone is defaulting to UTC. So in your example, it is storing the DateTime
in UTC, just 8 hours off from what you had expected.
Doing this
DateTime.new(2014,8,1,0,0,0, '+8')
DateTime.new(2014,8,-1,0,0,0, '+8')
DateTime.new(2014,8,1,0,0,0, '+8').getutc
DateTime.new(2014,8,-1,0,0,0, '+8').getutc
Will give this result
2014-08-01T00:00:00+08:00
2014-08-31T00:00:00+08:00
2014-07-31T16:00:00+00:00
2014-08-30T16:00:00+00:00
Here it is plugged into your code.
(1..8).each do |i|
self.create! name: "name#{i}", start_datetime: DateTime.new(2014,i,1,0,0,0, '+8').getutc, end_datetime: DateTime.new(2014,i,-1,0,0,0, '+8').getutc, location_id: 12
end
Upvotes: 0