rails: Date#to_time doesn't respect Time#use_zone

Steps to reproduce

# System clock should be in PDT
Time.use_zone('Eastern Time (US & Canada)') do
  d = Date.parse('friday')
  puts d.to_time
  puts d.to_time.zone

  t = Time.zone.parse('friday')
  puts t
  puts t.zone
end

Expected behavior

2016-06-17 00:00:00 -0400 EDT 2016-06-17 00:00:00 -0400 EDT

Actual behavior

2016-06-17 00:00:00 -0700 PDT 2016-06-17 00:00:00 -0400 EDT

System configuration

Rails version: Rails 4.2.3

Ruby version: ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin14.1.0]

Code Fix

In: date conversions

def to_time(form = :local)
  raise ArgumentError, "Expected :local or :utc, got #{form.inspect}." unless [:local, :utc].include?(form)
  ::Time.zone.send(form, year, month, day) # Time.zone.send instead of Time.zone
end

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 22 (7 by maintainers)

Most upvoted comments

You mean in latest Rails/Ruby, this crazy behaviour didn’t change?

Time.zone.name => UTC

Time.use_zone(“Samoa”) do t = Time.new(2017,1,1, 10,30,00) p t.to_time end

=> 2017-01-01 10:30:00 +0100

t.zone “W. Europe Standard Time”

Time.use_zone is not very useful here and I ended up having to pass time_zone to my function doing a Date.to_time