Skip to content

Commit

Permalink
fix behaviour for TimeWithZone#utc at end of DST
Browse files Browse the repository at this point in the history
- The #utc method should not raise an ambiguous time exception when converting
  a Teasy::TimeWithZone from local to utc since it knows the time zone and
  period.
- Add regression test
- Add test to assert that #in_time_zone at the start of DST returns a timestamp
  with DST period
  • Loading branch information
kaikuchn committed Jun 19, 2015
1 parent 09d17a7 commit 03671cb
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
14 changes: 13 additions & 1 deletion lib/teasy/time_with_zone.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ def self.from_utc(utc_time, zone = Teasy.default_zone)
from_time(utc_time, 'UTC').in_time_zone!(zone)
end

def self.parse(string, zone = Teasy.default_zone)
from_utc(Time.parse(string).utc, zone)
end

def self.iso8601(string, zone = Teasy.default_zone)
from_utc(Time.iso8601(string).utc, zone)
end

def self.strptime(string, format, zone = Teasy.default_zone)
new(*DateTime._strptime(string, format).values, 'UTC').in_time_zone!(zone)
end

def in_time_zone!(zone = Teasy.default_zone)
time = utc_time
@zone = TZInfo::Timezone.get(zone)
Expand All @@ -57,7 +69,7 @@ def utc?
end

def utc!
@time = @zone.local_to_utc(@time)
@time = @zone.local_to_utc(@time, @period.dst?)
@zone = TZInfo::Timezone.get('UTC')
@period = @zone.period_for_local(@time)
self
Expand Down
18 changes: 18 additions & 0 deletions test/teasy/time_with_zone_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,13 @@ def test_in_time_zone
refute_equal time.object_id, @timestamptz.in_time_zone('Asia/Calcutta')
end

def test_in_time_zone_at_dst_start
dst_start = Teasy::TimeWithZone.new(2014, 3, 30, 1)
.in_time_zone!('Europe/Berlin')
assert_equal 3, dst_start.hour
assert dst_start.dst?
end

def test_raises_on_ambiguous_time
dst_end = [2014, 10, 26, 2, 0, 0, 0, 'Europe/Berlin']
assert_raises(TZInfo::AmbiguousTime) do
Expand Down Expand Up @@ -382,6 +389,17 @@ def test_usec
assert_equal 1, @timestamptz_berlin.usec
end

def test_utc_at_dst_end
first_ambiguous_timestamp = Teasy::TimeWithZone.new(2014, 10, 26)
.in_time_zone 'Europe/Berlin'
assert_equal 2, first_ambiguous_timestamp.hour
assert_equal 0, first_ambiguous_timestamp.utc.hour
last_ambiguous_timestamp = Teasy::TimeWithZone.new(2014, 10, 26, 1)
.in_time_zone 'Europe/Berlin'
assert_equal 2, last_ambiguous_timestamp.hour
assert_equal 1, last_ambiguous_timestamp.utc.hour
end

def test_utc
assert_instance_of Teasy::TimeWithZone, @timestamptz.utc
assert_instance_of Teasy::TimeWithZone, @timestamptz_berlin.utc
Expand Down

0 comments on commit 03671cb

Please sign in to comment.