From 0607952ecafa3a9fbab27cdb95fa7dcf0044ea87 Mon Sep 17 00:00:00 2001 From: Michael Reinsch Date: Thu, 19 Jan 2023 12:11:37 +0100 Subject: [PATCH] easier way to subtract a duration from a time previous behaviour resulted in same as addition: ```ruby Fugit.parse('1Y') + Time.parse("2023-01-19T12:07:00T") # => 2024-01-19T12:07:00T Fugit.parse('1Y') - Time.parse("2023-01-19T12:07:00T") # => 2024-01-19T12:07:00T ``` With this change, the duration is now subtracted from the time: ```ruby Fugit.parse('1Y') + Time.parse("2023-01-19T12:07:00T") # => 2024-01-19T12:07:00T Fugit.parse('1Y') - Time.parse("2023-01-19T12:07:00T") # => 2022-01-19T12:07:00T ``` Mathematically this isn't quite correct I suppose, but neither is the current behaviour. --- lib/fugit/duration.rb | 2 +- spec/duration_spec.rb | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/fugit/duration.rb b/lib/fugit/duration.rb index bd662cf..92d03b3 100644 --- a/lib/fugit/duration.rb +++ b/lib/fugit/duration.rb @@ -269,7 +269,7 @@ def subtract(a) when Numeric then add_numeric(-a) when Fugit::Duration then add_duration(-a) when String then add_duration(-self.class.parse(a)) - when ::Time, ::EtOrbi::EoTime then add_to_time(a) + when ::Time, ::EtOrbi::EoTime then opposite.add_to_time(a) else fail ArgumentError.new( "cannot subtract #{a.class} instance to a Fugit::Duration") end diff --git a/spec/duration_spec.rb b/spec/duration_spec.rb index cddd2f0..a8f5b43 100644 --- a/spec/duration_spec.rb +++ b/spec/duration_spec.rb @@ -468,6 +468,15 @@ expect((d - s).to_plain_s).to eq('3h1s') end + it 'subtracts Time instances' do + + d = Fugit.parse('1Y2h') + t = Time.parse('2016-02-02T11:11:11Z') + + expect(Fugit.time_to_plain_s(d.subtract(t), false)).to eq('2015-02-02 09:11:11') + expect(Fugit.time_to_plain_s(d - t, false)).to eq('2015-02-02 09:11:11') + end + it 'fails else' do d = Fugit.parse('1Y2h')