From a6fa7c8d7e99c93301dabc54fb61a6e7ef1b0c44 Mon Sep 17 00:00:00 2001 From: Alexander Plavin Date: Thu, 18 Jul 2024 11:44:38 -0400 Subject: [PATCH] Support Date/Time + Unitful arithmetic (#731) --- src/dates.jl | 11 +++++++++++ test/dates.jl | 13 +++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/dates.jl b/src/dates.jl index eee39e48..baf33ebc 100644 --- a/src/dates.jl +++ b/src/dates.jl @@ -188,3 +188,14 @@ isapprox(x::AbstractArray{Dates.CompoundPeriod}, y::AbstractArray{<:AbstractQuan kwargs...) = isapprox(y, x; kwargs...) sleep(x::AbstractQuantity) = sleep(ustrip(s, x)) + +# Dates, Times, DateTimes + +for f in (:+, :-) + @eval Base.$f(x::Dates.DateTime, y::Quantity) = $f(x, trunc(Dates.Millisecond, y)) + @eval Base.$f(x::Dates.Time, y::Quantity) = $f(x, trunc(Dates.Nanosecond, y)) + @eval Base.$f(x::Dates.Date, y::Quantity) = $f(x, Dates.Day(y)) +end +Base.:+(y::Quantity, x::Dates.DateTime) = x + y +Base.:+(y::Quantity, x::Dates.Time) = x + y +Base.:+(y::Quantity, x::Dates.Date) = x + y diff --git a/test/dates.jl b/test/dates.jl index 0fff991f..0126ae17 100644 --- a/test/dates.jl +++ b/test/dates.jl @@ -31,6 +31,19 @@ @test 1.0u"wk" - Day(3) === 1.0u"wk" - Int64(3)u"d" @test_throws DimensionError 1u"m" + Second(1) @test_throws DimensionError 1u"m" - Second(1) + + @test Dates.Date(2000, 2, 3) + 24.0u"hr" == Dates.Date(2000, 2, 4) + @test Dates.Date(2000, 2, 3) + 48.0u"hr" == Dates.Date(2000, 2, 5) + @test_throws Exception Dates.Date(2000, 2, 3) + 1.0u"hr" + + @test Dates.DateTime(2000, 2, 3, 4, 5) + 1.0u"ns" == Dates.DateTime(2000, 2, 3, 4, 5) + @test Dates.DateTime(2000, 2, 3, 4, 5) + 23.0u"hr" == Dates.DateTime(2000, 2, 4, 3, 5) + @test Dates.DateTime(2000, 2, 3, 4, 5) + 100.0u"hr" == Dates.DateTime(2000, 2, 7, 8, 5) + @test Dates.Time(4, 5) + 1.0u"ps" == Dates.Time(4, 5) + @test Dates.Time(4, 5) + 1.0u"ms" == Dates.Time(4, 5, 0, 1) + @test Dates.Time(4, 5) + 1.5u"hr" == Dates.Time(5, 35) + @test Dates.Date(2000, 2, 5) - 48.0u"hr" == Dates.Date(2000, 2, 3) + @test 24.0u"hr" + Dates.Date(2000, 2, 5) == Dates.Date(2000, 2, 6) end @testset ">> Multiplication" begin