I was wondering how many years were between two events. So I define the timepoints, and find their difference:
julia> using Dates
julia> d0 = Date(1980, 6, 17)
1980-06-17
julia> d1 = Date(2015, 1, 4)
2015-01-04
julia> Δd = d1-d0
12619 days
I now wonder how many years and months this is, and try to convert it to a date:
julia> Date(Δd)
ERROR: ArgumentError: Day: 12619 out of range (1:31)
Stacktrace:
[1] Date(y::Int64, m::Int64, d::Int64)
@ Dates ~/.julia/juliaup/julia-1.10.0-beta3+0.x64.linux.gnu/share/julia/stdlib/v1.10/Dates/src/types.jl:257
[2] Date
@ Dates ~/.julia/juliaup/julia-1.10.0-beta3+0.x64.linux.gnu/share/julia/stdlib/v1.10/Dates/src/types.jl:305 [inlined]
[3] Date(::Day)
@ Dates ~/.julia/juliaup/julia-1.10.0-beta3+0.x64.linux.gnu/share/julia/stdlib/v1.10/Dates/src/types.jl:349
[4] top-level scope
@ REPL[33]:1
Okay, so I can not convert directly to date (this turns out to be false). So I google, and find this stackoverflow question. To convert more than 60 seconds to hours and minutes (similar problem), it reccomends an approach along the lines of
julia> Time(0) + Second(4000)
01:06:40
So I give that a shot:
julia> Δd + Date(0)
0034-07-20
Okay, so that works. But what happens here is just that Day(12619) is converted to Date:
julia> Δd + Date(0) |> typeof
Date
But that is what I attempted initially, with Date(Δd)! Or, that is what I thought. Apparently the two are different:
julia> convert(Date, Δd)
0035-07-20
I can see from using @code_lowered that Type(val) produces quite different code from convert(Type, val). Notably, the convert version produces significantly less code. My mental model was Type(val) essentially lowered to convert(Type, val), or the other way around. The examples with dates and times are the only cases where I have seen the effects from the difference.
An example of why I thought that they lowered to essentially the same is how the expressions below have similar stack traces and identical errors:
julia> Int(1.1)
ERROR: InexactError: Int64(1.1)
Stacktrace:
[1] Int64(x::Float64)
@ Base ./float.jl:909
[2] top-level scope
@ REPL[53]:1
julia> convert(Int, 1.1)
ERROR: InexactError: Int64(1.1)
Stacktrace:
[1] Int64
@ Base ./float.jl:909 [inlined]
[2] convert(::Type{Int64}, x::Float64)
@ Base ./number.jl:7
[3] top-level scope
@ REPL[52]:1
Could someone give me some interpretation as to why the two are different? Should they generally not be used interchangeably?