Skip to content

Commit cd200d1

Browse files
authored
Merge pull request #40803 from sostock/convert-compoundperiod-to-period
Enable conversion of `CompoundPeriod` to `Period`
2 parents b686e71 + ba3be5f commit cd200d1

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

stdlib/Dates/src/periods.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,9 @@ function Base.string(x::CompoundPeriod)
357357
end
358358
Base.show(io::IO,x::CompoundPeriod) = print(io, string(x))
359359

360+
Base.convert(::Type{T}, x::CompoundPeriod) where T<:Period =
361+
isconcretetype(T) ? sum(T, x.periods) : throw(MethodError(convert,(T,x)))
362+
360363
# E.g. Year(1) + Day(1)
361364
(+)(x::Period,y::Period) = CompoundPeriod(Period[x, y])
362365
(+)(x::CompoundPeriod, y::Period) = CompoundPeriod(vcat(x.periods, y))

stdlib/Dates/test/periods.jl

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -519,5 +519,18 @@ end
519519
#Test combined Fixed and Other Periods
520520
@test (1m + 1d < 1m + 1s) == false
521521
end
522+
523+
@testset "Convert CompoundPeriod to Period" begin
524+
@test convert(Month, Year(1) + Month(1)) === Month(13)
525+
@test convert(Second, Minute(1) + Second(30)) === Second(90)
526+
@test convert(Minute, Minute(1) + Second(60)) === Minute(2)
527+
@test convert(Millisecond, Minute(1) + Second(30)) === Millisecond(90_000)
528+
@test_throws InexactError convert(Minute, Minute(1) + Second(30))
529+
@test_throws MethodError convert(Month, Minute(1) + Second(30))
530+
@test_throws MethodError convert(Second, Month(1) + Second(30))
531+
@test_throws MethodError convert(Period, Minute(1) + Second(30))
532+
@test_throws MethodError convert(Dates.FixedPeriod, Minute(1) + Second(30))
533+
end
534+
522535
end
523536

0 commit comments

Comments
 (0)