Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.new with timezone (Rails)

DateTime.new takes a timezone parameter as the 7th argument as an integer offset.

DateTime.new(2001,2,3,4,5,6,'-7')

However, since I don't easily know whether a given time falls in Daylight or Standard, I would rather do something like:

DateTime.new(2001,2,3,4,5,6,'Eastern Time (US & Canada)')

Please advise

like image 238
jrhicks Avatar asked Jun 26 '14 19:06

jrhicks


2 Answers

If you're using Rails your best bet is:

cur_zone = Time.zone
begin
  Time.zone = 'Eastern Time (US & Canada)'
  datetime = Time.zone.local(2001, 2, 3, 4, 5, 6)
ensure
  Time.zone = cur_zone
end

Or if you've already set Time.zone when you authenticate your uses, or in your application.rb config file then you can just use the Time.zone.local line by itself.

like image 59
nzifnab Avatar answered Oct 22 '22 19:10

nzifnab


Idea found in: https://stackoverflow.com/a/41584881/3837660

In e.g. Rails 5.2.3

DateTime.included_modules.third
# => DateAndTime::Zones

which has #in_time_zone. (https://api.rubyonrails.org/classes/DateAndTime/Zones.html)

Allowing you to do the following:

#########################################
# Summer example
#
DateTime.new.in_time_zone(
  'Eastern Time (US & Canada)'
).change(
  year: 2017,
  month: 7,
  day: 31,
  hour: 7,
  min: 59,
  sec: 23
)
#
# => Mon, 31 Jul 2017 07:59:23 EDT -04:00
#
#########################################

#########################################
# Winter example
DateTime.new.in_time_zone(
  'Eastern Time (US & Canada)'
).change(
  year: 2017,
  month: 12,
  day: 31,
  hour: 7,
  min: 59,
  sec: 23
)
#
# => Sun, 31 Dec 2017 07:59:23 EST -05:00
#
#########################################

Note that DateTime#change is also an addition from Rails. See, e.g., https://api.rubyonrails.org/v5.2.3/classes/DateTime.html#method-i-change for details.

like image 28
sunless Avatar answered Oct 22 '22 19:10

sunless