How to convert Milliseconds to Int64?

The following is not working:

julia> diff=Dates.Millisecond(55)
55 milliseconds

julia> convert(Int64, diff)
ERROR: MethodError: Cannot `convert` an object of type Millisecond to an object of type Int64
Closest candidates are:
  convert(::Type{T}, ::Gray24) where T<:Real at ~/.julia/packages/ColorTypes/1dGw6/src/conversions.jl:114
  convert(::Type{T}, ::Gray) where T<:Real at ~/.julia/packages/ColorTypes/1dGw6/src/conversions.jl:113
  convert(::Type{T}, ::Base.TwicePrecision) where T<:Number at ~/packages/julias/julia-1.7/share/julia/base/twiceprecision.jl:262
  ...
Stacktrace:
 [1] top-level scope
   @ REPL[19]:1

julia> 

How can I make this work?

You can access the value field of any TimePeriod type which should already be an Int64

1 Like
julia> diff = Dates.Millisecond(55)
55 milliseconds

julia> Dates.value(diff)
55

julia> typeof(Dates.value(diff))
Int64
1 Like

A better error message when trying to use convert would be nice, though…

Maybe a PR for better documentation? I did a help in the REPL for Date and DateTime and none of the examples indicated how to extract the values from the representation.

Perhaps define Base.convert(Int, x::Period) = value(x) inside Dates.
That way there is no need to export value, and people who see convert generally know there is some type&value transformation happening.

using Dates

Base.convert(::Type{Int64}, x::Period) = Dates.value(x)
Base.convert(::Type{Integer}, x::Period) = Dates.value(x)
2 Likes