ironsand
ironsand

Reputation: 15161

How to taking time zone into account when using Date#to_time method

I have a Rails project that has Tokyo(+0900) time zone.

And OS local time zone is Bangkok(+0700).

Date#to_time method doesn't take time zone into account.

Date.current.to_time
2016-06-21 00:00:00 +0700

I'm using now Time.zone.parse method:

Time.zone.parse(Date.current.to_s)
Tue, 21 Jun 2016 00:00:00 JST +09:00

Is there a better way to convert a date to time with the proper time zone?

Time.zone

Time.zone
#<ActiveSupport::TimeZone:0x007fa8402f86f0 @name="Tokyo", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: Asia/Tokyo>, @current_period=#<TZInfo::TimezonePeriod: #<TZInfo::TimezoneTransitionDefinition: #<TZInfo::TimeOrDateTime: -578044800>,#<TZInfo::TimezoneOffset: 32400,0,JST>>,nil>>

config/application.rb

module MyProject
  class Application < Rails::Application
   config.time_zone = 'Tokyo'
  end
end

Upvotes: 2

Views: 1465

Answers (2)

varunvlalan
varunvlalan

Reputation: 950

This has been fixed in Ruby 2.4

https://wyeworks.com/blog/2016/6/22/behavior-changes-in-ruby-2.4

Upvotes: 3

Sampat Badhe
Sampat Badhe

Reputation: 9075

to_time by default takes local time zone to convert the time in time zone, and it accepts only :local or :utc time zone in the parameter. so you have to set the time zone before you apply .to_time on Date object.

Time.zone = "Tokyo"
irb(main):046:0> Date.current.to_time
=> Tue, 21 Jun 2016 09:00:00 JST +09:00

OR you can user .use_zone with the block to keep that set that time zone for the particular block.

irb(main):046:0> Time.use_zone("Tokyo"){Date.current.to_time}
=> Tue, 21 Jun 2016 09:00:00 JST +09:00

Above result will always give you time with respect to UTC so time will be added with respect to selected time zone. if you want it to be set to start of the day you can use beginning_of_day

Time.zone = "Tokyo"
irb(main):048:0> Date.current.to_time.beginning_of_day
=> Tue, 21 Jun 2016 00:00:00 JST +09:00

irb(main):049:0> Time.use_zone("Tokyo"){ Date.current.to_time.beginning_of_day }
=> Tue, 21 Jun 2016 00:00:00 JST +09:00

Using Date object for Time Zone operations is not a better approach, always use Time object to deal with Time Zone

Time.zone = "Tokyo"

irb(main):050:0> Time.zone.now.beginning_of_day
=> Tue, 21 Jun 2016 00:00:00 ICT +09:00

irb(main):051:0> Time.use_zone("Tokyo"){ Time.zone.now.beginning_of_day }
=> Tue, 21 Jun 2016 00:00:00 JST +09:00

Do’s and Don’ts of Rails Timezones

Upvotes: 1

Related Questions