Skip to content

Commit 66c50ac

Browse files
TheLostLambdainkydragonomus
authored
Allow Times to be rounded to Periods (#52629)
Co-authored-by: CyHan <git@wo-class.cn> Co-authored-by: Curtis Vogt <curtis.vogt@gmail.com>
1 parent 349f142 commit 66c50ac

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

stdlib/Dates/src/rounding.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,12 @@ function Base.floor(dt::DateTime, p::TimePeriod)
8484
return epochms2datetime(milliseconds - mod(milliseconds, value(Millisecond(p))))
8585
end
8686

87+
function Base.floor(t::Time, p::TimePeriod)
88+
value(p) < 1 && throw(DomainError(p))
89+
nanoseconds = value(t)
90+
return Time(Nanosecond(nanoseconds - mod(nanoseconds, value(Nanosecond(p)))))
91+
end
92+
8793
"""
8894
floor(x::Period, precision::T) where T <: Union{TimePeriod, Week, Day} -> T
8995

stdlib/Dates/test/rounding.jl

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,27 @@ end
188188
@test round(x, Dates.Microsecond) == Dates.Microsecond(2001000)
189189
@test round(x, Dates.Nanosecond) == x
190190
end
191-
191+
@testset "Rounding Time" begin
192+
x = Time(9, 25, 45, 25, 650, 500)
193+
@test floor(x, Dates.Hour) == Time(9)
194+
@test floor(x, Dates.Minute) == Time(9, 25)
195+
@test floor(x, Dates.Second) == Time(9, 25, 45)
196+
@test floor(x, Dates.Millisecond) == Time(9, 25, 45, 25)
197+
@test floor(x, Dates.Microsecond) == Time(9, 25, 45, 25, 650)
198+
@test floor(x, Dates.Nanosecond) == x
199+
@test ceil(x, Dates.Hour) == Time(10)
200+
@test ceil(x, Dates.Minute) == Time(9, 26)
201+
@test ceil(x, Dates.Second) == Time(9, 25, 46)
202+
@test ceil(x, Dates.Millisecond) == Time(9, 25, 45, 26)
203+
@test ceil(x, Dates.Microsecond) == Time(9, 25, 45, 25, 651)
204+
@test ceil(x, Dates.Nanosecond) == x
205+
@test round(x, Dates.Hour) == Time(9)
206+
@test round(x, Dates.Minute) == Time(9, 26)
207+
@test round(x, Dates.Second) == Time(9, 25, 45)
208+
@test round(x, Dates.Millisecond) == Time(9, 25, 45, 26)
209+
@test round(x, Dates.Microsecond) == Time(9, 25, 45, 25, 651)
210+
@test round(x, Dates.Nanosecond) == x
211+
end
192212
@testset "Rounding DateTime to Date" begin
193213
now_ = DateTime(2020, 9, 1, 13)
194214
for p in (Year, Month, Day)

0 commit comments

Comments
 (0)