From 9831354a4e26101372b89ed4d84576f358390cf1 Mon Sep 17 00:00:00 2001 From: Iblis Lin Date: Mon, 22 Oct 2018 01:33:56 +0800 Subject: [PATCH] Dates: add constructor DateTime(::Date, ::Time) --- stdlib/Dates/src/types.jl | 21 ++++++++++++++++++++- stdlib/Dates/test/arithmetic.jl | 10 ++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/stdlib/Dates/src/types.jl b/stdlib/Dates/src/types.jl index c0202bd9171b3a..30bf3c7007bde7 100644 --- a/stdlib/Dates/src/types.jl +++ b/stdlib/Dates/src/types.jl @@ -240,7 +240,7 @@ function DateTime(y::Year, m::Month=Month(1), d::Day=Day(1), h::Hour=Hour(0), mi::Minute=Minute(0), s::Second=Second(0), ms::Millisecond=Millisecond(0)) return DateTime(value(y), value(m), value(d), - value(h), value(mi), value(s), value(ms)) + value(h), value(mi), value(s), value(ms)) end Date(y::Year, m::Month=Month(1), d::Day=Day(1)) = Date(value(y), value(m), value(d)) @@ -310,6 +310,25 @@ function Time(period::TimePeriod, periods::TimePeriod...) return Time(h, mi, s, ms, us, ns) end +# Convenience constructor for DateTime from Date and Time +""" + DateTime(d::Date, t::Time) + +Construct a `DateTime` type by `Date` and `Time`. + +```jldoctest +julia> d = Date(2018, 1, 1) +2018-01-01 + +julia> t = Time(8, 15, 42) +08:15:42 + +julia> DateTime(d, t) +2018-01-01T08:15:42 +``` +""" +DateTime(dt::Date, t::Time) = dt + t + # Fallback constructors DateTime(y, m=1, d=1, h=0, mi=0, s=0, ms=0) = DateTime(Int64(y), Int64(m), Int64(d), Int64(h), Int64(mi), Int64(s), Int64(ms)) Date(y, m=1, d=1) = Date(Int64(y), Int64(m), Int64(d)) diff --git a/stdlib/Dates/test/arithmetic.jl b/stdlib/Dates/test/arithmetic.jl index ac27cfea1190d6..87be3670224e02 100644 --- a/stdlib/Dates/test/arithmetic.jl +++ b/stdlib/Dates/test/arithmetic.jl @@ -299,6 +299,16 @@ end @test dt - Dates.Day(100) == Dates.Date(1999, 9, 18) @test dt - Dates.Day(1000) == Dates.Date(1997, 4, 1) end + @testset "Date-Time arithmetic" begin + dt = Dates.Date(1999, 12, 27) + @test dt + Dates.Time(0, 0, 0) == Dates.DateTime(1999, 12, 27, 0, 0, 0) + @test dt + Dates.Time(1, 0, 0) == Dates.DateTime(1999, 12, 27, 1, 0, 0) + @test dt + Dates.Time(0, 1, 0) == Dates.DateTime(1999, 12, 27, 0, 1, 0) + @test dt + Dates.Time(0, 0, 1) == Dates.DateTime(1999, 12, 27, 0, 0, 1) + + t = Dates.Time(0, 0, 0) + Dates.Hour(24) + @test dt + t == Dates.DateTime(1999, 12, 27, 0, 0, 0) + end end @testset "Time-TimePeriod arithmetic" begin t = Dates.Time(0)