Skip to content

Commit a6fa7c8

Browse files
authored
Support Date/Time + Unitful arithmetic (#731)
1 parent b80ab85 commit a6fa7c8

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

src/dates.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,3 +188,14 @@ isapprox(x::AbstractArray{Dates.CompoundPeriod}, y::AbstractArray{<:AbstractQuan
188188
kwargs...) = isapprox(y, x; kwargs...)
189189

190190
sleep(x::AbstractQuantity) = sleep(ustrip(s, x))
191+
192+
# Dates, Times, DateTimes
193+
194+
for f in (:+, :-)
195+
@eval Base.$f(x::Dates.DateTime, y::Quantity) = $f(x, trunc(Dates.Millisecond, y))
196+
@eval Base.$f(x::Dates.Time, y::Quantity) = $f(x, trunc(Dates.Nanosecond, y))
197+
@eval Base.$f(x::Dates.Date, y::Quantity) = $f(x, Dates.Day(y))
198+
end
199+
Base.:+(y::Quantity, x::Dates.DateTime) = x + y
200+
Base.:+(y::Quantity, x::Dates.Time) = x + y
201+
Base.:+(y::Quantity, x::Dates.Date) = x + y

test/dates.jl

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,19 @@
3131
@test 1.0u"wk" - Day(3) === 1.0u"wk" - Int64(3)u"d"
3232
@test_throws DimensionError 1u"m" + Second(1)
3333
@test_throws DimensionError 1u"m" - Second(1)
34+
35+
@test Dates.Date(2000, 2, 3) + 24.0u"hr" == Dates.Date(2000, 2, 4)
36+
@test Dates.Date(2000, 2, 3) + 48.0u"hr" == Dates.Date(2000, 2, 5)
37+
@test_throws Exception Dates.Date(2000, 2, 3) + 1.0u"hr"
38+
39+
@test Dates.DateTime(2000, 2, 3, 4, 5) + 1.0u"ns" == Dates.DateTime(2000, 2, 3, 4, 5)
40+
@test Dates.DateTime(2000, 2, 3, 4, 5) + 23.0u"hr" == Dates.DateTime(2000, 2, 4, 3, 5)
41+
@test Dates.DateTime(2000, 2, 3, 4, 5) + 100.0u"hr" == Dates.DateTime(2000, 2, 7, 8, 5)
42+
@test Dates.Time(4, 5) + 1.0u"ps" == Dates.Time(4, 5)
43+
@test Dates.Time(4, 5) + 1.0u"ms" == Dates.Time(4, 5, 0, 1)
44+
@test Dates.Time(4, 5) + 1.5u"hr" == Dates.Time(5, 35)
45+
@test Dates.Date(2000, 2, 5) - 48.0u"hr" == Dates.Date(2000, 2, 3)
46+
@test 24.0u"hr" + Dates.Date(2000, 2, 5) == Dates.Date(2000, 2, 6)
3447
end
3548

3649
@testset ">> Multiplication" begin

0 commit comments

Comments
 (0)