Skip to content

Commit

Permalink
Allow Times to be rounded to Periods (#52629)
Browse files Browse the repository at this point in the history
Co-authored-by: CyHan <[email protected]>
Co-authored-by: Curtis Vogt <[email protected]>
  • Loading branch information
3 people authored Nov 4, 2024
1 parent 349f142 commit 66c50ac
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
6 changes: 6 additions & 0 deletions stdlib/Dates/src/rounding.jl
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,12 @@ function Base.floor(dt::DateTime, p::TimePeriod)
return epochms2datetime(milliseconds - mod(milliseconds, value(Millisecond(p))))
end

function Base.floor(t::Time, p::TimePeriod)
value(p) < 1 && throw(DomainError(p))
nanoseconds = value(t)
return Time(Nanosecond(nanoseconds - mod(nanoseconds, value(Nanosecond(p)))))
end

"""
floor(x::Period, precision::T) where T <: Union{TimePeriod, Week, Day} -> T
Expand Down
22 changes: 21 additions & 1 deletion stdlib/Dates/test/rounding.jl
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,27 @@ end
@test round(x, Dates.Microsecond) == Dates.Microsecond(2001000)
@test round(x, Dates.Nanosecond) == x
end

@testset "Rounding Time" begin
x = Time(9, 25, 45, 25, 650, 500)
@test floor(x, Dates.Hour) == Time(9)
@test floor(x, Dates.Minute) == Time(9, 25)
@test floor(x, Dates.Second) == Time(9, 25, 45)
@test floor(x, Dates.Millisecond) == Time(9, 25, 45, 25)
@test floor(x, Dates.Microsecond) == Time(9, 25, 45, 25, 650)
@test floor(x, Dates.Nanosecond) == x
@test ceil(x, Dates.Hour) == Time(10)
@test ceil(x, Dates.Minute) == Time(9, 26)
@test ceil(x, Dates.Second) == Time(9, 25, 46)
@test ceil(x, Dates.Millisecond) == Time(9, 25, 45, 26)
@test ceil(x, Dates.Microsecond) == Time(9, 25, 45, 25, 651)
@test ceil(x, Dates.Nanosecond) == x
@test round(x, Dates.Hour) == Time(9)
@test round(x, Dates.Minute) == Time(9, 26)
@test round(x, Dates.Second) == Time(9, 25, 45)
@test round(x, Dates.Millisecond) == Time(9, 25, 45, 26)
@test round(x, Dates.Microsecond) == Time(9, 25, 45, 25, 651)
@test round(x, Dates.Nanosecond) == x
end
@testset "Rounding DateTime to Date" begin
now_ = DateTime(2020, 9, 1, 13)
for p in (Year, Month, Day)
Expand Down

0 comments on commit 66c50ac

Please sign in to comment.