Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable conversion of CompoundPeriod to Period #40803

Merged
merged 1 commit into from
Aug 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions stdlib/Dates/src/periods.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
13 changes: 13 additions & 0 deletions stdlib/Dates/test/periods.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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