Skip to content

Commit

Permalink
easier way to subtract a duration from a time
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mreinsch committed Jan 19, 2023
1 parent 9b1c6b1 commit 0607952
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/fugit/duration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions spec/duration_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down

0 comments on commit 0607952

Please sign in to comment.