Alexander Gorg
Alexander Gorg

Reputation: 1078

From where Rails take their DateTime.now?

Recently I wanted to change updated_at column of a post, but it's not that simple!

Nevertheless, server time is 12:06 and when I use console (irb) it is 12:06 Also tried:

irb(main):001:0> Time.zone.to_s
=> "(GMT+03:00) Moscow"

Still when I do :

post.update!(updated_at: DateTime.now)
=> true

And if I retrieve the record, the result is "2018-10-29 09:06:47"

Any help is appreciated!

Upvotes: 3

Views: 113

Answers (1)

SRack
SRack

Reputation: 12203

Try using DateTime.current - that will get the zoned time if your app is operating in one.

From the docs:

Returns Time.zone.now.to_datetime when Time.zone or config.time_zone are set, otherwise returns Time.now.to_datetime.

Basically, Time.zone should reflect DateTime.current if you're working with a time zone, while Time.now and DateTime.now will ignore any zone. The method's source is quite self explanatory here:

def current
  ::Time.zone ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime
end

Hope that helps - give me a shout if you've any questions.

Upvotes: 3

Related Questions