From ba3be5f5cfb2e23d35d467a11118d62c79aa8fb5 Mon Sep 17 00:00:00 2001 From: Sebastian Stock <42280794+sostock@users.noreply.github.com> Date: Wed, 12 May 2021 14:47:50 +0200 Subject: [PATCH] Enable conversion of CompoundPeriod to Period --- stdlib/Dates/src/periods.jl | 3 +++ stdlib/Dates/test/periods.jl | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/stdlib/Dates/src/periods.jl b/stdlib/Dates/src/periods.jl index 22c792cb2f333..61df01302521b 100644 --- a/stdlib/Dates/src/periods.jl +++ b/stdlib/Dates/src/periods.jl @@ -357,6 +357,9 @@ function Base.string(x::CompoundPeriod) end Base.show(io::IO,x::CompoundPeriod) = print(io, string(x)) +Base.convert(::Type{T}, x::CompoundPeriod) where T<:Period = + isconcretetype(T) ? sum(T, x.periods) : throw(MethodError(convert,(T,x))) + # E.g. Year(1) + Day(1) (+)(x::Period,y::Period) = CompoundPeriod(Period[x, y]) (+)(x::CompoundPeriod, y::Period) = CompoundPeriod(vcat(x.periods, y)) diff --git a/stdlib/Dates/test/periods.jl b/stdlib/Dates/test/periods.jl index 81aacd1a9e54b..3bb310be4ee84 100644 --- a/stdlib/Dates/test/periods.jl +++ b/stdlib/Dates/test/periods.jl @@ -519,5 +519,18 @@ end #Test combined Fixed and Other Periods @test (1m + 1d < 1m + 1s) == false end + +@testset "Convert CompoundPeriod to Period" begin + @test convert(Month, Year(1) + Month(1)) === Month(13) + @test convert(Second, Minute(1) + Second(30)) === Second(90) + @test convert(Minute, Minute(1) + Second(60)) === Minute(2) + @test convert(Millisecond, Minute(1) + Second(30)) === Millisecond(90_000) + @test_throws InexactError convert(Minute, Minute(1) + Second(30)) + @test_throws MethodError convert(Month, Minute(1) + Second(30)) + @test_throws MethodError convert(Second, Month(1) + Second(30)) + @test_throws MethodError convert(Period, Minute(1) + Second(30)) + @test_throws MethodError convert(Dates.FixedPeriod, Minute(1) + Second(30)) +end + end