Skip to content

Commit

Permalink
Merge pull request #40803 from sostock/convert-compoundperiod-to-period
Browse files Browse the repository at this point in the history
Enable conversion of `CompoundPeriod` to `Period`
  • Loading branch information
quinnj authored Aug 3, 2021
2 parents b686e71 + ba3be5f commit cd200d1
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
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

0 comments on commit cd200d1

Please # to comment.