Skip to content

Instantly share code, notes, and snippets.

@viniciussbs
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viniciussbs/873705cd80cc51dc579b to your computer and use it in GitHub Desktop.
Save viniciussbs/873705cd80cc51dc579b to your computer and use it in GitHub Desktop.
Full-day period taking into account the time zone (tested in Rails 4.2.0.beta2)
# I'm in Brasilia time zone: BRT -03:00 (or BRTS -02:00 during Daylighy Saving Time).
Time.zone.name
#=> "Brasilia"
# Get time with time zone:
yesterday = Time.zone.now.yesterday
#=> Tue, 28 Oct 2014 17:04:11 BRST -02:00
# Full-day period with time zone:
yesterday.all_day
#=> Tue, 28 Oct 2014 00:00:00 BRST -02:00..Tue, 28 Oct 2014 23:59:59 BRST -02:00
# ActiveRecord converts to UTC (with `time.to_s(:db)`, probably):
Contest.where(created_at: yesterday.all_day).to_sql
#=> "SELECT `contests`.* FROM `contests` WHERE (`contests`.`created_at` BETWEEN '2014-10-28 02:00:00' AND '2014-10-29 01:59:59')"
# Now I can get all contests created at yesterday:
y Contest.where(created_at: yesterday.all_day).pluck(:created_at).uniq
#---
#- 2014-10-28 02:00:40.000000000 Z
#- 2014-10-28 03:00:40.000000000 Z
#- 2014-10-28 04:00:40.000000000 Z
#- 2014-10-28 05:00:40.000000000 Z
#- 2014-10-28 06:00:40.000000000 Z
#- 2014-10-28 07:00:40.000000000 Z
#- 2014-10-28 08:00:40.000000000 Z
#- 2014-10-28 09:00:40.000000000 Z
#- 2014-10-28 10:00:41.000000000 Z
#- 2014-10-28 11:00:40.000000000 Z
#- 2014-10-28 12:00:40.000000000 Z
#- 2014-10-28 13:00:40.000000000 Z
#- 2014-10-28 14:00:40.000000000 Z
#- 2014-10-28 15:00:40.000000000 Z
#- 2014-10-28 16:00:40.000000000 Z
#- 2014-10-28 17:00:40.000000000 Z
#- 2014-10-28 18:00:40.000000000 Z
#- 2014-10-28 19:00:40.000000000 Z
#- 2014-10-28 20:00:40.000000000 Z
#- 2014-10-28 21:00:39.000000000 Z
#- 2014-10-28 22:00:40.000000000 Z
#- 2014-10-28 23:00:39.000000000 Z
#- 2014-10-29 01:00:40.000000000 Z
#=> nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment