diff --git a/Project.toml b/Project.toml index d23b55e..ce5a89f 100644 --- a/Project.toml +++ b/Project.toml @@ -1,7 +1,7 @@ name = "UnixTimes" uuid = "ab1a18e7-b408-4913-896c-624bb82ed7f4" authors = ["Christian Rorvik "] -version = "1.4.1" +version = "1.5.0" [deps] Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" diff --git a/src/UnixTimes.jl b/src/UnixTimes.jl index 198d330..d5468d2 100644 --- a/src/UnixTimes.jl +++ b/src/UnixTimes.jl @@ -63,11 +63,24 @@ UnixTime(x::Date) = UnixTime(DateTime(x)) UnixTime(x::Date, y::Time) = UnixTime(year(x), month(x), day(x), hour(y), minute(y), second(y), millisecond(y), microsecond(y), nanosecond(y)) +const DATEFORMAT = dateformat"yyyy-mm-ddTHH:MM:SS.sss" + +function UnixTime(s::AbstractString) + try + @assert length(s) == 29 + dt = DateTime(chop(s; tail=6), DATEFORMAT) + ns = Nanosecond(parse(Int, last(s, 6))) + UnixTime(dt) + ns + catch + throw(ArgumentError("Invalid UnixTime string")) + end +end + Base.convert(::Type{UnixTime}, x::DateTime) = UnixTime(x) function Base.show(io::IO, x::UnixTime) xdt = convert(DateTime, x) - print(io, Dates.format(xdt, dateformat"yyyy-mm-ddTHH:MM:SS.sss")) + print(io, Dates.format(xdt, DATEFORMAT)) v = x.instant.periods.value d = 100_000 for i in 1:6 diff --git a/test/runtests.jl b/test/runtests.jl index 19b5d3e..ef499a8 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -47,6 +47,10 @@ end @testset "io" begin x = UnixTime(2020, 1, 2, 3, 4, 5, 6, 7, 8) @test string(x) == "2020-01-02T03:04:05.006007008" + @test UnixTime(string(x)) == x + @test_throws ArgumentError UnixTime("2025-01-28T15:49:36.5901397023") + @test_throws ArgumentError UnixTime("2025-01-28T15:49:36.59013970") + @test_throws ArgumentError UnixTime(repeat("a", 29)) end @testset "arithmetic" begin