Rails custom TimeZone - ruby-on-rails

How can I set my rails application with custom timezone? I want to set my application timezone with UTC-04:00 without daylight saving.
update: To clarify my question, I understand that I can set the time zone name in the environment.rb file with one of the names from TimeZone constants. I want my application timezone as UTC -04:00 without daylight saving.
Thanks,
Soe Moe

Suppose you want a timezone that does NOT use DST, and basically tracks Eastern Standard Time always (also known as Eastern Prevailing Time). You want it to be a -05:00 offset always.
Use the Timezone Etc/GMT+5. Rails will lazy-load timezones not in its normal list from TZInfo, so you can cherry pick from: http://tzinfo.rubyforge.org/svn/trunk/tzinfo/lib/tzinfo/definitions/Etc/
Here are some examples to prove this, in my Rails 3.2 rails console:
Daylight Savings example. October 4 is daylight savings time. You would expect your hours to be off by one for Eastern time and your special timezone. 2011-10-05 04:57:23 in UTC should be 2011-10-05 00:57:23 Eastern Daylight Time.
1.9.3p0 :014 > DateTime.civil(2011,10,5,4,57,23)
=> Wed, 05 Oct 2011 04:57:23 +0000
1.9.3p0 :015 > DateTime.civil(2011,10,5,4,57,23).in_time_zone('Eastern Time (US & Canada)')
=> Wed, 05 Oct 2011 00:57:23 EDT -04:00
1.9.3p0 :016 > DateTime.civil(2011,10,5,4,57,23).in_time_zone('Etc/GMT+5')
=> Tue, 04 Oct 2011 23:57:23 GMT+5 -05:00
Non-Daylight Savings example. December 1 is standard time. You would expect Eastern time and your custom "always EST" to be equivalent. 2011-12-01 02:30:45 should be 2011-11-30 21:30:45 in both EST and your special timezone.
1.9.3p0 :010 > DateTime.civil(2011,12,1,2,30,45)
=> Thu, 01 Dec 2011 02:30:45 +0000
1.9.3p0 :012 > DateTime.civil(2011,12,1,2,30,45).in_time_zone('Eastern Time (US & Canada)')
=> Wed, 30 Nov 2011 21:30:45 EST -05:00
1.9.3p0 :013 > DateTime.civil(2011,12,1,2,30,45).in_time_zone('Etc/GMT+5')
=> Wed, 30 Nov 2011 21:30:45 GMT+5 -05:00
Why is it GMT+5 and not GMT-5? I'm not entirely sure. I would have expected it to be GMT-5, but this is how the etc timezones seem to work in TZInfo.

Normally you'd only want to do this when the location you live in doesn't practice Daylight Savings Time. In your particular case, you're in luck, and can use the "La Paz" timezone. According to this website, it doesn't practice DST.
You can always run rake time:zones:all and see what UTC offsets correspond to the offset you're interested in using. Then google those offsets to see if they change during the year.
I don't know of a general method to tell Rails you want UTC +/- a fixed offset.

Related

Rails Time Zone: How to pass time zone configured in application.rb file as parameter to the to_datetime method?

I configured my time zone to indian time zone in my Rails app by adding this line config.time_zone = 'Mumbai' to my application.rb file.
I am having a date time field t.datetime :check_in in my table. To this check_in column I am saving the server time like this Person.check_in = DateTime.now. When I save like this, the time is saving properly, with the time zone configured in the app. after that for some reason when I update like this Person.check_in = "24/08/2015 11:50 AM".to_datetime it is not saving the time with the time zone I configured. Below is my rails console output:
prashant#prashant-pc:~/client_proj/template$ rails c
Loading development environment (Rails 4.1.5)
2.2.2 :001 > check_in = DateTime.now
=> Mon, 24 Aug 2015 11:41:16 +0530
2.2.2 :003 > "24/08/2015 11:42 PM".to_datetime
=> Mon, 24 Aug 2015 23:42:00 +0000
2.2.2 :004 >
This is unfortunately the designed behavior of to_datetime function.
This other question is what you are after. They provide the following alternatives:
Time.zone.parse('24/08/2015 11:50 AM').to_datetime
or even:
"24/08/2015 11:50 AM".to_datetime.in_time_zone("Mumbai")
Use in_time_zone from ActiveSupport::TimeWithZone
"2015-08-14 14:38".to_datetime.in_time_zone('Mumbai')
=> Fri, 14 Aug 2015 20:08:00 IST +05:30
"2015-08-14 14:38".to_datetime.in_time_zone('Eastern Time (US & Canada)')
=> Fri, 14 Aug 2015 10:38:00 EDT -04:00
Time.now.in_time_zone("Mumbai")
=> Sat, 22 Aug 2015 12:38:32 IST +05:30
Time.now.in_time_zone("Pacific Time (US & Canada)")
=> Sat, 22 Aug 2015 00:08:21 PDT -07:00
Actually, there are several ways to do the same thing e.g. using Time.zone.local, Time.zone.parse etc. See the above link for more examples.
To, answer your exact question, to pass the time_zone configured in your application.rb file, you have to use this:
check_in = DateTime.now
check_in.in_time_zone(Rails.application.config.time_zone).to_datetime
Use local time gem. It will display the time in local time zone no matter where you are.
It is very good solution as you will don't have to call in time zone method every time you show a date in your views. The Gem has very good documentation as well. Visit https://github.com/basecamp/local_time

How can I convert a Time from some timezone to UTC, taking into account Daylight Saving, in Ruby?

I have an app where different users are in different parts of the globe (I know their timezone), and they can enter dates and times, and I need to store everything in UTC on the DB.
Normally to instance my Time variable, I'm doing:
DateTime.new(date.year, date.month, date.day, hours, minutes, 0)
This is already in UTC, but without converting.
If I add a 7th parameter to that string with the time_zone (ie. "Melbourne"), then it will interpret it as a a date in Australia, and the resulting DateTime, when converted to UTC, is 10-ish hours behind, and that works.
However, that's not taking into account Daylight Saving.
What I need is to do exactly that (instance a DateTime from the components of a date/time), such that (in the case of Australia, for example), using the same hours/minutes for April 9th will give me a different offset when converted to UTC than if I used April 5th.
Any ideas?
Thanks!
Daniel
Have a look at tzinfo
irb(main):002:0> require 'tzinfo'
=> true
irb(main):003:0> tz = TZInfo::Timezone.get("Australia/Melbourne")
=> #<TZInfo::DataTimezone: Australia/Melbourne>
irb(main):004:0> tz.utc_to_local(Time.parse("2013-04-05 00:00:00"))
=> Fri Apr 05 11:00:00 UTC 2013
irb(main):005:0> tz.utc_to_local(Time.parse("2013-04-09 00:00:00"))
=> Tue Apr 09 10:00:00 UTC 2013
irb(main):015:0> tz.local_to_utc(Time.parse("2013-04-09 00:00:00"))
=> Mon Apr 08 14:00:00 UTC 2013
irb(main):016:0> tz.local_to_utc(Time.parse("2013-04-05 00:00:00"))
=> Thu Apr 04 13:00:00 UTC 2013

How can EDT be -4:00?

Loading development environment (Rails 3.0.17)
1.9.3p194 :001 > Time.zone
=> (GMT-05:00) Eastern Time (US & Canada)
1.9.3p194 :002 > Time.now.in_time_zone
=> Tue, 18 Sep 2012 14:16:00 EDT -04:00
1.9.3p194 :003 > wtf....
Unless all of my apps are doing this (only have one to test right now) how can EDT be -04:00 from UTC instead of the normal -05:00
Whatever is causing this -04:00 is causing my deadline based app to have all the countdown timers NOT appear for anyone other than EST users. Like if you selected CST in my app, saved, and then viewed the same page again, you'd have one hour less on the countdown... so if the gig was going off in an hour and you did it, well you wouldn't be able to join.
Not good.
Thoughts?
EDT (Eastern Daylight Time) is GMT -4:00
If you look at the result, you're seeing EDT rather than EST (which is GMT -5:00).

Correcting time for daylight savings in rails DateTime.parse

Just adding to the million questions about time zone and DST issues out there.
I have a form with separate date and time fields that I combine to create a DateTime like so
start_time = DateTime.parse("#{parse_date(form_date)} #{form_start_time} #{Time.zone}")
If I fill out my form with 21 Aug 2012 and 15:00, then these are the values that I see when I reload my form. If I then look at my start_time attribute in my model it is correctly set to Tue, 21 Aug 2012 15:00:00 EST +10:00.
The problem I am having occurs if I use a date later this year once daylight savings kicks in (I am in Australia). If I use 21 Dec 2012 and 15:00 then check start_time I see Fri, 21 Dec 2012 16:00:00 EST +11:00.
My interpretation of the problem is that the date is being saved in my current time zone (+10:00) as this is what I have told DateTime.parse to do. However when the value is returned, Rails is looking at the date and saying 'hey, it's daylight savings time in December' and returning the time in the +11:00 time zone.
What I want to do is tell DateTime.parse to save the time in the +11:00 time zone if DST is in effect. Clearly passing Time.zone into my string doesn't achieve this. Is there a simple way of doing this? I can see ways of doing it using Time#dst? but I suspect that this is going to create some really ugly convoluted code. I thought there might be a built in way that I'm missing.
(Answer for Rails 4.2.4, didn't check for older or newer versions)
Instead of using fixed shift +01:00, +02:00, etc, I recommend to use the in_time_zone String method with time zone name as argument :
Summer time :
ruby :001 > "2016-07-02 00:00:00".in_time_zone('Paris')
=> Sat, 02 Jul 2016 00:00:00 CEST +02:00
Winter time :
ruby :002 > "2016-11-02 00:00:00".in_time_zone('Paris')
=> Wed, 02 Nov 2016 00:00:00 CET +01:00
String#in_time_zone is the equivalent of :
ruby :003 > Time.find_zone!("Paris").parse("2016-07-02 00:00:00")
=> Sat, 02 Jul 2016 00:00:00 CEST +02:00
ruby :004 > Time.find_zone!("Paris").parse("2016-11-02 00:00:00")
=> Wed, 02 Nov 2016 00:00:00 CET +01:00
You can get the time zone names by :
$ rake time:zones:all
Or in rails console :
ruby :001 > ActiveSupport::TimeZone.all.map(&:name)
Or build collection for select tag :
ActiveSupport::TimeZone.all.map do |timezone|
formatted_offset = Time.now.in_time_zone(timezone.name).formatted_offset
[ "(GMT#{formatted_offset}) #{timezone.name}", timezone.name ]
end
And store the time zone name instead of the shift.
Note : don't confuse String#in_time_zone method and the Time#in_time_zone method.
consider the time zone for my system is 'Paris'.
ruby :001 > Time.parse("2016-07-02 00:00:00")
=> 2016-07-02 00:00:00 +0200
ruby :002 > Time.parse("2016-07-02 00:00:00").in_time_zone("Nuku'alofa")
=> Sat, 02 Jul 2016 11:00:00 TOT +13:00
Here's my solution so far. I'm hoping someone has a better one.
start_time = DateTime.parse "#{date} #{(form_start_time || start_time)} #{Time.zone}"
start_time = start_time - 1.hour if start_time.dst? && !Time.now.dst?
start_time = start_time + 1.hour if Time.now.dst? && start_time.dst?
It seems to work but I haven't rigorously tested it. I suspect it could be prettied up and shortened but I think this is readable and understandable. Any improvements?
I ran into this exact issue. My app allows users to see upcoming events. In the US we fall of DST on November 2nd and all events on and after that date were showing times an hour early.
We require the opportunity to have the timezone selected and stored to its own field. Before I was using the following to store my datetime:
timezone_offset = Time.now.in_time_zone(params[:opportunity][:time_zone]).strftime("%z") #-0700
DateTime.parse("#{params[:opportunity][:start_datetime]} #{timezone_offset}")
To fix the issue I have changed to:
start_datetime = Time.zone.parse(params[:opportunity][:start_datetime])
To display the correct times we use:
#opportunity.start_datetime.in_time_zone(#opportunity.time_zone)
I wouuld try and use
Australian Eastern Standard Time (AEST) (UTC +10).
Australian Central Standard Time (ACST) (UTC +9 ½).
Australian Western Standard Time (AWST) (UTC +8).
which adjust for Daylight Savings.
With Rails, we can use ActiveSupport::TimeZone for this:
tz = ActiveSupport::TimeZone.new 'Pacific Time (US & Canada)'
tz.parse(date_str_without_zone).to_datetime
I use TZip to get TimeZone strings (e.g. "Pacific Time (US & Canada)") from zip codes.
In case you have a custom date/time format, different than the supported by String#in_time_zone, you could also use (since rails 5) strptime like:
Time.find_zone!('Auckland').strptime('2021-02-02 08.00.00', '%Y-%m-%d %H.%M.%S')

Set timezone for incoming xml data

I'm getting a datetime field from an API that does not explicitly set its timezone. When I place this into a database it's assuming the datetime must be in GMT, but the timezone is actually in Chicago time. (I say Chicago time, because I'm still unsure if this API factors in DST.) What is the best way for me to convert this time to GMT before adding it to the database?
Here is an XML sample of one of the nodes I'm referring to:
<FromDateTime>2011-03-17 08:00:00</FromDateTime>
In Ruby, I'm using this to add this record to the database.
:starttime => DateTime.parse(row.at_xpath("FromDateTime/text()").to_s),
I think what I need to do is add the difference in hours between CST and GMT to this last Ruby call, right? How would I do that?
Thanks!
Could you use Time instead? DateTime is not Daylight Savings Time aware. Time automatically sets to your local GMT offset for the given date/time and set DST if needed.
irb(main):014:0> require 'time'
irb(main):015:0> Time.parse('2011-03-17 08:00:00')
=> Thu Mar 17 08:00:00 -0400 2011
irb(main):022:0> Time.parse('2011-03-17 08:00:00').dst?
=> true
Here is the case for standard time (I am in EST)
irb(main):025:0> Time.parse('2011-01-17 08:00:00')
=> Mon Jan 17 08:00:00 -0500 2011
irb(main):023:0> Time.parse('2011-01-17 08:00:00').dst?
=> false
If you are using ActiveSupport http://api.rubyonrails.org/classes/DateTime.html you can set to arbitrary time zone:
irb(main):039:0> Time.zone = 'America/Chicago'
=> "America/Chicago"
irb(main):040:0> Time.parse('2011-03-17 08:00:00')
=> Thu Mar 17 08:00:00 -0400 2011

Resources