Skip to content

Commit

Permalink
Return the correct seconds since the epoch value for strftime with %s.
Browse files Browse the repository at this point in the history
%s was being deferred to the result of the conversion to local. This is
actually a UTC instance being used to represent local time, so the
result would be the number of seconds since the epoch plus the total UTC
offset.

Override the handling of %s and use the passed in UTC instance to
calculate the value.

Resolves #91.
  • Loading branch information
philr committed Aug 30, 2018
1 parent cccd70b commit fe9b204
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
10 changes: 7 additions & 3 deletions lib/tzinfo/timezone.rb
Expand Up @@ -573,15 +573,19 @@ def current_period_and_time
# depending on the version of Ruby in use (for example, %:::z is only
# supported by Time#strftime from MRI version 2.0.0 onwards.)
def strftime(format, utc = Time.now.utc)
utc = TimeOrDateTime.wrap(utc)
period = period_for_utc(utc)
local = period.to_local(utc)
local = Time.at(local).utc unless local.kind_of?(Time) || local.kind_of?(DateTime)
local_wrapped = period.to_local(utc)
local = local_wrapped.to_orig
local = local_wrapped.to_time unless local.kind_of?(Time) || local.kind_of?(DateTime)
abbreviation = period.abbreviation.to_s.gsub(/%/, '%%')

format = format.gsub(/%(%*)(Z|:*z)/) do
format = format.gsub(/%(%*)([sZ]|:*z)/) do
if $1.length.odd?
# Escaped literal percent or series of percents. Pass on to strftime.
"#$1%#$2"
elsif $2 == "s"
"#$1#{utc.to_i}"
elsif $2 == "Z"
"#$1#{abbreviation}"
else
Expand Down
3 changes: 3 additions & 0 deletions test/tc_timezone.rb
Expand Up @@ -1260,6 +1260,7 @@ def test_strftime_datetime
assert_equal('BST BST', tz.strftime('%Z %Z', dt))
assert_equal('BST %Z %BST %%Z %%BST', tz.strftime('%Z %%Z %%%Z %%%%Z %%%%%Z', dt))
assert_equal('+0100 +01:00 +01:00:00 +01 %::::z', tz.strftime('%z %:z %::z %:::z %::::z', dt))
assert_equal('1153001522 %s %1153001522', tz.strftime('%s %%s %%%s', dt))
end

def test_strftime_time
Expand All @@ -1271,6 +1272,7 @@ def test_strftime_time
assert_equal('BST BST', tz.strftime('%Z %Z', t))
assert_equal('BST %Z %BST %%Z %%BST', tz.strftime('%Z %%Z %%%Z %%%%Z %%%%%Z', t))
assert_equal('+0100 +01:00 +01:00:00 +01 %::::z', tz.strftime('%z %:z %::z %:::z %::::z', t))
assert_equal('1153001522 %s %1153001522', tz.strftime('%s %%s %%%s', t))
end

def test_strftime_int
Expand All @@ -1282,6 +1284,7 @@ def test_strftime_int
assert_equal('BST BST', tz.strftime('%Z %Z', i))
assert_equal('BST %Z %BST %%Z %%BST', tz.strftime('%Z %%Z %%%Z %%%%Z %%%%%Z', i))
assert_equal('+0100 +01:00 +01:00:00 +01 %::::z', tz.strftime('%z %:z %::z %:::z %::::z', i))
assert_equal('1153001522 %s %1153001522', tz.strftime('%s %%s %%%s', i))
end

def test_get_missing_data_source
Expand Down

0 comments on commit fe9b204

Please sign in to comment.