Skip to content

Commit

Permalink
simplify and harden conversion from Period to floating-point seconds
Browse files Browse the repository at this point in the history
  • Loading branch information
baumgold committed Jun 1, 2023
1 parent e2513d7 commit 8b0947c
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
4 changes: 4 additions & 0 deletions stdlib/Dates/src/periods.jl
Original file line number Diff line number Diff line change
Expand Up @@ -465,3 +465,7 @@ days(c::Year) = 365.2425 * value(c)
days(c::Quarter) = 91.310625 * value(c)
days(c::Month) = 30.436875 * value(c)
days(c::CompoundPeriod) = isempty(c.periods) ? 0.0 : Float64(sum(days, c.periods))
seconds(x::Nanosecond) = value(x) / 1000000000
seconds(x::Microsecond) = value(x) / 1000000
seconds(x::Millisecond) = value(x) / 1000
seconds(x::Period) = value(Second(x))
6 changes: 3 additions & 3 deletions stdlib/Dates/src/types.jl
Original file line number Diff line number Diff line change
Expand Up @@ -460,14 +460,14 @@ Base.hash(x::Time, h::UInt) =
hash(hour(x), hash(minute(x), hash(second(x),
hash(millisecond(x), hash(microsecond(x), hash(nanosecond(x), h))))))

Base.sleep(duration::Period) = sleep(toms(duration) / 1000)
Base.sleep(duration::Period) = sleep(seconds(duration))

function Base.Timer(delay::Period; interval::Period=Second(0))
Timer(toms(delay) / 1000, interval=toms(interval) / 1000)
Timer(seconds(delay), interval=seconds(interval))
end

function Base.timedwait(testcb, timeout::Period; pollint::Period=Millisecond(100))
timedwait(testcb, toms(timeout) / 1000, pollint=toms(pollint) / 1000)
timedwait(testcb, seconds(timeout), pollint=seconds(pollint))
end

Base.OrderStyle(::Type{<:AbstractTime}) = Base.Ordered()
Expand Down
9 changes: 9 additions & 0 deletions stdlib/Dates/test/periods.jl
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,15 @@ end
@test Dates.days(Dates.Hour(24)) == 1
@test Dates.days(d) == 1
@test Dates.days(w) == 7

@test Dates.seconds(ns) == 0.000000001
@test Dates.seconds(us) == 0.000001
@test Dates.seconds(ms) == 0.001
@test Dates.seconds(s) == 1
@test Dates.seconds(mi) == 60
@test Dates.seconds(h) == 3600
@test Dates.seconds(d) == 86400
@test Dates.seconds(w) == 604800
end
@testset "issue #9214" begin
@test 2s + (7ms + 1ms) == (2s + 7ms) + 1ms == 1ms + (2s + 7ms) == 1ms + (1s + 7ms) + 1s == 1ms + (2s + 3d + 7ms) + (-3d) == (1ms + (2s + 3d)) + (7ms - 3d) == (1ms + (2s + 3d)) - (3d - 7ms)
Expand Down

0 comments on commit 8b0947c

Please sign in to comment.