Ruby/Rails Time.parse in input timezone - ruby-on-rails

I have a string that contains ISO8601 formatted date and time with timezone. How can I get Time or TimeWithTimezone object in the timezone specified in the string?
PC's timezone is '+01:00' and ActiveSupport::TimeWithZone is set to UTC. Here's what I've tried so far:
Loading development environment (Rails 3.2.13)
irb(main):001:0> Time.parse '1990-01-23T00:11:22-07:00'
=> 1990-01-23 08:11:22 +0100
irb(main):002:0> Time.zone.parse '1990-01-23T00:11:22-07:00'
=> Tue, 23 Jan 1990 07:11:22 UTC +00:00
Here's what I want:
irb(main):001:0> Time.???? '1990-01-23T00:11:22-07:00'
=> 1990-01-23 00:11:22 -0700
How can I parse the string and get time object in the timezone specified in the string?

Your issue was that you've used Time, whereas had to use DateTime:
DateTime.strptime('1990-01-23T00:11:22-07:00', "%Y-%m-%dT%H:%M:%S%z")
#=> Tue, 23 Jan 1990 00:11:22 -0700
EDIT
To make it a Time class object, you can do something like this (somewhat ugly, but still it does its job):
date = DateTime.strptime('1990-01-23T00:11:22-07:00', "%Y-%m-%dT%H:%M:%S%z")
#=> Tue, 23 Jan 1990 00:11:22 -0700
Time.new(date.year, date.month, date.day, date.hour, date.min, date.sec, date.zone)
#=> 1990-01-23 00:11:22 -0700

Related

Rails - Is there an easy way to check if British Summer Time and GMT are different?

I've been reading Rails BST timezone implementation however the method listed doesn't seem to work any more:
Time.zone = 'London'
Time.now = 2017-04-10 15:47:45 +0100
Time.zone = 'Cairo'
Time.now = 2017-04-10 15:47:45 +0100
This is clearly wrong. Is there an easy way for me to check? My end result is trying to see if the London timezone has +0100 in it or not, could I simply do Time.now.include?('+0100')
Thanks in advance
the method listed doesn't seem to work any more
You're using the wrong method:
Time.now is a Ruby method returning a "plain" Time instance.
Time.zone.now is a Rails method returning a ActiveSupport::TimeWithZone instance.
There's also a shortcut Time.current:
Time.zone = 'London'
Time.zone.now
#=> Mon, 10 Apr 2017 15:54:35 BST +01:00
Time.current
#=> Mon, 10 Apr 2017 15:54:35 BST +01:00
With another time zone:
Time.zone = 'Cairo'
Time.zone.now
#=> Mon, 10 Apr 2017 16:54:35 EET +02:00
My end result is trying to see if the London timezone has +0100 in it or not
In that case "+0100" indicates daylight saving time. The proper method is dst?:
t1 = Time.zone.parse('2017-03-26') #=> Sun, 26 Mar 2017 00:00:00 GMT +00:00
t2 = Time.zone.parse('2017-03-27') #=> Mon, 27 Mar 2017 00:00:00 BST +01:00
t1.dst? #=> false
t2.dst? #=> true

Fix timezone issue with database in Rails on Heroku

My Rails app is hosted on Heroku with a Postgress database. For a certain model I'm asking the user to chose a day and a time, which I combine to a date before saving the model:
def create_timestamp
self.date = day.to_datetime + time.seconds_since_midnight.seconds
end
When I chose for instance today # 20:50:00 and store it in the database, my record looks like this:
<Report id: 1, account_id: 1, date: "2016-11-05 20:50:00", description: "test", created_at: "2016-11-05 19:50:57", updated_at: "2016-11-05 19:50:57", deleted_at: nil, user_id: 1, report_category_id: 2, time: "2000-01-01 20:50:00", day: "2016-11-05">
As you might notice, the created_at date is different, because it's in a different timezone. While the created_at is stored in UTC +0000, my custom date, which uses local timezone is CET +0100.
So when I type in console: Report.find(1).date, it returns 2016-11-05 21:50:00 +0100.
How can I store the correct date in the initial set, or make the database return the correct timezone when querying?
Thanks
What you're doing currently is basically this:
>> date = Date.new(2016, 11, 6)
=> Sun, 06 Nov 2016
>> time = Time.new(2000, 1, 1, 20, 50, 0)
=> 2000-01-01 20:50:00 +0100
>> date.to_datetime + time.seconds_since_midnight.seconds
=> Sun, 06 Nov 2016 20:50:00 +0000
to_datetime converts the time-zone-less Date into a DateTime representing midnight UTC on that date, and then you add 20 hours and 50 minutes.
Instead of midnight UTC, you want midnight in your local time zone as your starting point. So you could do this, for example:
>> date.in_time_zone + time.seconds_since_midnight.seconds
=> Sun, 06 Nov 2016 20:50:00 CET +01:00
Rails should then be smart enough to convert it to UTC when storing in the database and back to CET when retrieving from the database.
To be clear about the difference, compare:
>> date
=> Sun, 06 Nov 2016
>> date.to_datetime
=> Sun, 06 Nov 2016 00:00:00 +0000
>> date.in_time_zone
=> Sun, 06 Nov 2016 00:00:00 CET +01:00
You should use
Time.zone.now
# or
Time.current
Which will return the time in time zone

How to save a date into rails using the console

I have a table that has a date field in it. How would I save the date using the console? I tried
event = Event.create(name:"Concert", date:08/20/2016, location:'Portland', state:'OR')
However, I am getting an Invalid octal digit error.
You'll want to pass in an actual Date object, which you can get from a string with the Date.parse method:
event = Event.create(name: "Concert", date: Date.parse('2016-08-20'), location: 'Portland', state: 'OR')
Note that I've rewritten your date to be in a different format. The MM/DD/YYYY format is not portable across locales, so I'd strongly suggest you use YYYY-MM-DD (the ISO 8601 format).
Using a string in the correct format will do the trick. For example:
>> foo = Foo.create date: "20/8/2016"
(0.0ms) begin transaction
SQL (1.0ms) INSERT INTO "foos" ("date") VALUES (?) [["date", Sat, 20 Aug 2016]]
(0.9ms) commit transaction
#<Foo id: 1, date: "2016-08-20">
>> foo.date
Sat, 20 Aug 2016
ActiveSupport provides core extensions on the String class for conversions from strings to date, time, and datetime. This is probably ok, and more convenient, to take advantage of while testing around in Rails console.
Taking advantage of this extension in the application itself (instead of explicitly parsing with Date.parse) is totally up to you and your team.
From the source:
"1-1-2012".to_date # => Sun, 01 Jan 2012
"01/01/2012".to_date # => Sun, 01 Jan 2012
"2012-12-13".to_date # => Thu, 13 Dec 2012
"12/13/2012".to_date # => ArgumentError: invalid date
Just to be thorough, examples for String#to_time
"13-12-2012".to_time # => 2012-12-13 00:00:00 +0100
"06:12".to_time # => 2012-12-13 06:12:00 +0100
"2012-12-13 06:12".to_time # => 2012-12-13 06:12:00 +0100
"2012-12-13T06:12".to_time # => 2012-12-13 06:12:00 +0100
"2012-12-13T06:12".to_time(:utc) # => 2012-12-13 06:12:00 UTC
"12/13/2012".to_time # => ArgumentError: argument out of range
And String#to_datetime:
"1-1-2012".to_datetime # => Sun, 01 Jan 2012 00:00:00 +0000
"01/01/2012 23:59:59".to_datetime # => Sun, 01 Jan 2012 23:59:59 +0000
"2012-12-13 12:50".to_datetime # => Thu, 13 Dec 2012 12:50:00 +0000
"12/13/2012".to_datetime # => ArgumentError: invalid date
Try this, for example:
date = Date.parse('3rd Feb 2001') ####=> #<Date: 2001-02-03 ...>
Reference: Date class

Rails: DateTime of different time zones

I have a project model with a datetime attribute to define the deadline. The deadlines are of different time zones, and I receive them in a string format like below:
Jan 1st 2013 00:00:00 EST
Feb 9th 2013 23:59:00 PST
I want to store these values in the default UTC format in the database. I've seen that there are many options to parse the time like Time.zone.parse and Time.parse. My question is: what's the best practice to parse the datetime of different time zones? I'm using Rails 3.2.9.
You need not worry about that at all, as long as you set correct timezone in config/application.rb:
config.time_zone = 'UTC'
You just assign the time strings to the attributes, ActiveRecord will convert it correctly.
1.9.3p125 :002 > project.deadline = "Jan 1st 2013 00:00:00 EST"
=> "Jan 1st 2013 00:00:00 EST"
1.9.3p125 :003 > project.deadline
=> Tue, 01 Jan 2013 05:00:00 UTC +00:00
1.9.3p125 :004 > project.deadline = "Feb 9th 2013 23:59:00 PST"
=> "Feb 9th 2013 23:59:00 PST"
1.9.3p125 :005 > project.deadline
=> Sun, 10 Feb 2013 07:59:00 UTC +00:00
ActiveRecord uses Time.zone.parse to parse the strings internally.
When you run Time.parse it will convert the timestamp to your configured timezone in rails. For example, my rails app runs in EST.
[5] pry(main)> Time.parse('Jan 1st 2013 00:00:00 EST')
=> 2013-01-01 00:00:00 -0500
[6] pry(main)> Time.parse('Feb 9th 2013 23:59:00 PST')
=> 2013-02-10 02:59:00 -0500
Notice the +3:00hrs for the PST timestamp used to get the result into my EST timezone.
To get the UTC version of each timestamp, just call utc
[7] pry(main)> Time.parse('Jan 1st 2013 00:00:00 EST').utc
=> 2013-01-01 05:00:00 UTC
[8] pry(main)> Time.parse('Feb 9th 2013 23:59:00 PST').utc
=> 2013-02-10 07:59:00 UTC

Preserving timezones in Rails

If I have a time string of the form "Wed, 22 Jun 2011 09:43:58 +0200" coming from a client, I wish to store it with the time zone preserved. This is important because it's not just the absolute UTC time that is important but also the timezone.
Time.zone.parse(t) will convert the time to whatever the zone that Time.zone is using at the time, losing the source timezone.
Do I have to manually extract the timezone from the above string or is there an idiomatic way to do this?
A DateTime field can only store 'YYYY-MM-DD HH:MM:SS' (MySQL), no Time Zone info.
You should store the datetime in UTC, and the Timezone in a different field, preferably as an integer specifying the offset from UTC in minutes.
You can extract the offset like this:
ruby-1.9.2-p180:001:0>> require 'active_support/all' # included by Rails by default
# => true
ruby-1.9.2-p180:002:0>> dt = DateTime.parse "Wed, 22 Jun 2011 09:43:58 +0200"
# => Wed, 22 Jun 2011 09:43:58 +0200
ruby-1.9.2-p180:003:0>> dt.utc_offset
# => 7200
ruby-1.9.2-p180:004:0>> dt.utc
# => Wed, 22 Jun 2011 07:43:58 +0000
EDIT:
And to round trip the excercise
ruby-1.9.2-p180 :039 > u.utc.new_offset(u.offset)
=> Wed, 22 Jun 2011 09:43:58 +0500
ruby-1.9.2-p180 :040 > u
=> Wed, 22 Jun 2011 09:43:58 +0500
I think you are looking for the following solution:
In ApplicationController:
before_filter :get_tz
def get_tz
#tz = current_user.time_zone
end
def use_tz
Time.use_zone #tz do
yield
end
end
And in a controller add around filter at the beginnig
around_filter :use_tz

Resources