Is there a Ruby 1.8.7 time.strftime %z bug? - ruby-on-rails

I'm having an issue with Ruby 1.8.7 strftime where the %z is returning the local time after i convert the time to UTC.
I'm doing the following:
>> t = Time.now
=> Mon Dec 19 15:20:16 -0800 2011
>> t.strftime("%z")
=> "-0800"
>> t = Time.now.utc
=> Mon Dec 19 23:20:28 UTC 2011
>> t.strftime("%z")
=> "-0800"
Even after I change the time to UTC, the timezone formatted gets defaulted to my local PST -0800.
Is this a known issue? Is there a way around it?

Note that the fine 1.8.7 manual makes no mention of %z:
...
%w - Day of the week (Sunday is 0, 0..6)
%x - Preferred representation for the date alone, no time
%X - Preferred representation for the time alone, no date
%y - Year without a century (00..99)
%Y - Year with century
%Z - Time zone name
%% - Literal ``%'' character
but the 1.9.3 version does have documented support for %z:
Time zone:
%z - Time zone as hour and minute offset from UTC (e.g. +0900)
%:z - hour and minute offset from UTC with a colon (e.g. +09:00)
%::z - hour, minute and second offset from UTC (e.g. +09:00:00)
%Z - Time zone abbreviation name
The fact the %z produces anything at all appears to be an undocumented and possibly accidental implementation detail.
You can use %Z in 1.8.7 and 1.9.3; for example, you get these results in 1.8.7:
>> t = Time.now
=> Mon Dec 19 16:46:06 -0800 2011
>> t.zone
=> "PST"
>> t.strftime('%z %Z')
=> "-0800 PST"
>> t = Time.now.utc
=> Tue Dec 20 00:46:27 UTC 2011
>> t.zone
=> "UTC"
>> t.strftime('%z %Z')
=> "-0800 UTC"
That will give you the timezone as UTC, PST, EDT, and similar common abbreviations. If you want the offset, you should be using gmt_offset in both 1.9.3 and 1.8.7:
>> Time.now.gmt_offset
=> -28800
>> Time.now.utc.gmt_offset
=> 0
Note that gmt_offset gives you the offset in seconds.

Your problem.
ruby-1.9.2-p290 :004 > Time.now.strftime("%z")
=> "-0500"
ruby-1.9.2-p290 :005 > Time.now.utc.strftime("%z")
=> "+0000"

Related

Why is %Z giving me the numeric offset instead of the abbreviated time zone name in Ruby?

I'm trying to parse a timestamp from a string, and then subsequently display it with its abbreviated time zone, but what's coming back is the numeric offset from UTC despite what I believe is the correct usage. Here's the console session:
[5] pry(main)> time_string = "2022-08-02T12:00:00 CDT"
=> "2022-08-02T12:00:00 CDT"
[6] pry(main)> DateTime.parse(time_string).zone
=> "-05:00"
[7] pry(main)> DateTime.parse(time_string).strftime("%Z")
=> "-05:00"
What I'm expecting here is that this will return CDT again.
This is Ruby 2.7 on macOS, with Rails:
❯ ruby --version
ruby 2.7.2p137 (2020-10-01 revision 5445e04352) [x86_64-darwin21]
❯ rails --version
Rails 6.1.6
From the strftime docs for rails, says it's working as intended.
Time zone:
%z - Time zone as hour and minute offset from UTC (e.g. +0900)
%:z - hour and minute offset from UTC with a colon (e.g. +09:00)
%::z - hour, minute and second offset from UTC (e.g. +09:00:00)
%:::z - hour, minute and second offset from UTC
(e.g. +09, +09:30, +09:30:30)
%Z - Equivalent to %:z (e.g. +09:00)
If you have the actual timezone name you can use that to get the abbreviation as outline here in the blog post
def human_timezone(time_string, timezone)
time = time_string.in_time_zone(timezone)
if time.zone.match?(/^\w/)
time.zone
else
time.formatted_offset
end
end
>> human_timezone('2019-03-28 16:00', 'Pacific Time (US & Canada)')
=> "PDT"
>> human_timezone('2019-03-28 16:00', 'Berlin')
=> "CET"
>> human_timezone('2019-05-01 16:00', 'Almaty')
=> "+06:00"
Ruby doesn't store timezone name, it stores only the time offset (-5:00).
So, backward conversion is not possible because there are multiple timezones for one offset. For e.g. another timezone with -5:00 offset.
> time_string = "2022-08-02T12:00:00 PET"
=> "2022-08-02T12:00:00 PET"
> DateTime.parse time_string
=> Tue, 02 Aug 2022 12:00:00 -0500

Convert Active Support timezone original format into a string

I'm trying to convert Active Support timezone original format into a string. I want to store it in an array of characters then parse each needed data individually.
Time.zone = current_user.timezone
date_and_time = Time.zone.now
Now
date_and_time = Thu, 21 Apr 2016 20:58:04 PDT -07:00
Ruby method ( to_s ) does not convert it. I found other ways to convert it to but all of them will change the format to numbers only, I want the day to stay the same because I will store it in a variable then use it in a different method.
You can use .to_formatted_s(DATE_FORMAT) for this.
time = Time.now # => Thu Jan 18 06:10:17 CST 2007
time.to_formatted_s(:db) # => "2007-01-18 06:10:17"
time.to_formatted_s(:long) # => "January 18, 2007 06:10"
time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10"
time.to_formatted_s(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600"
time.to_formatted_s(:iso8601) # => "2007-01-18T06:10:17-06:00"
A list of all DATE_FORMATS and more information can be found here:
http://api.rubyonrails.org/classes/Time.html#method-i-to_formatted_s
You can try this
date_and_time.strftime("%a %d %b %Y")
Also You can check this guide, to get format you want
You should get what you want using this :
date_and_time.strftime("%a %d %b %Y %H:%M:%S UTC %:z")
Please see strftime Docs for more info
Explanation
Reason for hardcoding UTC is so that according to the docs
%z - Time zone as hour and minute offset from UTC
So i believe it should be UTC all the time.

Ruby on Rails time zone strange behaviour

There is task model with attributes when and duration.
create_table "tasks", force: true do |t|
...
t.datetime "when"
t.integer "duration"
...
end
I wrote method for checking if task is active so I can show it on page.
This is active method:
def active?
if (self.when + self.duration) > Time.now
true
end
end
I tried in console to inspect object:
t.when + t.duration
=> Sun, 08 Sep 2013 01:01:00 UTC +00:00
DateTime.now
=> Sun, 08 Sep 2013 01:57:13 +0200
t.active?
=> true
It's true but I entered 1:00 time and 1 minute for duration and I hoped it shouldn't be true.
It seems that when column in database is not saved in correct time zone, so it gives incorrect results. How to solve this issue?
It seems that when column in database is not saved in correct time zone
1) Rails automatically converts times to UTC time before inserting them in the database (which is a good thing), which means the times have an offset of "+0000" . That means if you save a time of 8pm to the database, and your server is located in a timezone with an offset of "+0600", then the equivalent UTC time is 2pm, so 2pm gets saved in the database. In other words, your local server's time is 6 hours ahead of UTC time, which means that when it's 8pm in your server's time zone, it's 2pm in the UTC timezone.
2) When you compare dates, ruby takes the timezone offset into account--in other words ruby converts all times to the same timezone and then compares the times. Here is an example:
2.0.0p247 :086 > x = DateTime.strptime('28-01-2013 08:00:00 PM +6', '%d-%m-%Y %I:%M:%S %p %z')
=> Mon, 28 Jan 2013 20:00:00 +0600
2.0.0p247 :087 > y = DateTime.strptime('28-01-2013 08:20:00 PM +7', '%d-%m-%Y %I:%M:%S %p %z')
=> Mon, 28 Jan 2013 20:20:00 +0700
2.0.0p247 :088 > x < y
=> false
If you just compare the times of the two Datetime objects, x is less than y. However, y has a time of 8:20pm in a timezone that has an offset of +7, which is equivalent to the time 7:20pm in a timezone with an offset of +6. Therefore, y is actually less than x. You need to compare apples to apples, which means you need to mentally compare times that have been converted to the same timezone to get the same results as ruby/rails produces.
3) You can convert Time.now to a UTC time using the rails utc() method:
2.0.0p247 :089 > x = Time.now
=> 2013-09-07 8:00:00 +0600
2.0.0p247 :090 > x.utc
=> 2013-09-07 02:00:00 UTC
That's what ruby does before comparing Time.now to task.when + task.duration
4) You might find it more convenient to create a DateTime object with the time you want using:
DateTime.strptime('28-01-2013 08:00:00 PM +0', '%d-%m-%Y %I:%M:%S %p %z'
Because you are able to specify the offset as zero, you don't have to create a time that anticipates the conversion to UTC time.
Or you can use the change() method, which causes the offset() to change without converting the time:
2.0.0p247 :011 > x = DateTime.now
=> Sun, 08 Sep 2013 00:34:08 +0600
2.0.0p247 :012 > x.change offset: "+0000"
=> Sun, 08 Sep 2013 00:34:08 +0000
ActiveRecord stores timestamps in UTC by default. See How to change default timezone for Active Record in Rails? for changing default time zone.
You can also just use Time#in_time_zone to convert t.when to your timezone, see http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html.

Rails Time class has a TimeZone Bug. Can this be confirmed?

Here goes :
Time.zone.now => "Eastern Time (US & Canada)"
Time.zone.now => Wed, 15 Aug 2012 06:05:37 EDT -04:00
Time.zone.now + 39.years => Tue, 15 Aug 2051 06:06:03 EST -05:00
And so you have it, the end of our fabled Eastern Daylight Time has been prophesied by Ruby on Rails to end in the year 2051.
Also works for any other TimeZone changing area.
Time.zone
=> "Pacific Time (US & Canada)"
1.9.2p180 :003 > Time.zone.now
=> Wed, 15 Aug 2012 03:08:57 PDT -07:00
1.9.2p180 :004 > Time.zone.now + 39.years
=> Tue, 15 Aug 2051 03:08:57 PST -08:00
This exists in Rails 3.0 and in Rails 3.2.6
Yes, it looks like a bug. It's not Rails, however, it's the Ruby Time class. It has problems with times after 2038.
For example, with Ruby 1.8.7:
> Time.local(2037,8,16,9,30,15)
=> Sun Aug 16 09:30:15 -0400 2037
>
> Time.local(2038,8,16,9,30,15)
=> Mon Aug 16 09:30:15 -0500 2038
JRuby 1.6.7.2 - for instance - does not have this problem:
> Time.local(2038,8,16,9,30,15)
=> Mon Aug 16 09:30:15 -0400 2038
Note that, on MRI Ruby on 64-bit systems, the ActiveSupport time extension which supports the addition of durations ultimately calls Time.local or Time.utc via this method in active_support/core_ext/time/calculations.rb:
# Returns a new Time if requested year can be accommodated by Ruby's Time class
# (i.e., if year is within either 1970..2038 or 1902..2038, depending on system architecture);
# otherwise returns a DateTime
def time_with_datetime_fallback(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0, usec=0)
::Time.send(utc_or_local, year, month, day, hour, min, sec, usec)
rescue
offset = utc_or_local.to_sym == :local ? ::DateTime.local_offset : 0
::DateTime.civil(year, month, day, hour, min, sec, offset)
end
I guess the issue is that for years >= 2038, they were expecting an overflow exception and for DateTime to be used instead. On 64-bit systems, this doesn't happen.
UPDATE: This analysis is incorrect for Ruby 1.9.2+. Time.local works as expected, but the original problem still occurs.

Ruby String to_time broken?

I would expect Time and to_time to be reflective.
UPDATE
This is the answer, if you add the parameter :local, it doesn't ignore the offset. I find it wierd that it ignores data (the offset) by default, though...
Time.zone.now.to_s.to_time(:local) returns 2012-03-20 14:39:03 +0100
/UPDATE
> Time.zone.now.to_s
=> "2012-03-20 12:50:05 +0100"
> Time.zone.now.to_s.to_time.to_s
=> "2012-03-20 12:50:05 UTC"
# PROBLEM:
# UTC is +0000, meaning that there is 1 hour diff in the above
> Time.zone.now
=> Tue, 20 Mar 2012 12:51:32 CET +01:00
> Time.zone.now.to_time
=> Tue, 20 Mar 2012 12:51:32 CET +01:00
> Time.zone.now.to_json
=> "\"2012-03-20T12:50:36+01:00\""
> Time.zone.now.to_json.to_time
=> 2012-03-20 12:50:36 UTC
I have this problem with JSON messages. Anyway, I wouldn't expect to_time to actually change the time. OK to translate to UTC, probably, but it should adjust time accordingly. Anybody know if this is a known issue or "by design"?
This method, String#to_time, defined in ActiveSupport takes one parameter, form, which can be either :utc (default) or :local. So by default, it always returns a Time in UTC.
To get a Time with timezone:
Time.zone.parse("2012-03-20T12:50:36+01:00")

Resources