Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails compare Time with TimeWithZone

In my Rails app, I'm comparing a date from my database to Time.now:

Event.date_start >= Time.now

But Event.date_start is ActiveSupport::TimeWithZone

Everything works perfectly but I want to know if comparing a Time with a TimeWithZone is the proper way, and if this is not the case, how to do it?

like image 507
Alexandre Avatar asked Sep 18 '25 02:09

Alexandre


2 Answers

The best practice is not to use Time.now in Rails apps. Use Time.current instead. It returns ActiveSupport::TimeWithZone too.

like image 161
mikdiet Avatar answered Sep 20 '25 16:09

mikdiet


Time.now also works with TimeZone. Look at this:

Time.zone.now
#=> Mon, 12 Sep 2016 16:51:54 UTC +00:00

ExampleModel.date_start
#=> Tue, 28 Jun 2016 12:39:26 UTC +00:00

Time.zone
#=> #<ActiveSupport::TimeZone:0x0055de104e3ce0 @name="UTC", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: Etc/UTC>, @current_period=#<TZInfo::TimezonePeriod: nil,nil,#<TZInfo::TimezoneOffset: 0,0,UTC>>>>

You can compare this without restrictions :)

like image 45
Bartłomiej Gładys Avatar answered Sep 20 '25 18:09

Bartłomiej Gładys