Skip to content

Commit ba82223

Browse files
authored
Add UnixTime parsing from string #11
2 parents 66811e2 + 68a5e1f commit ba82223

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

Project.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
name = "UnixTimes"
22
uuid = "ab1a18e7-b408-4913-896c-624bb82ed7f4"
33
authors = ["Christian Rorvik <[email protected]>"]
4-
version = "1.4.1"
4+
version = "1.5.0"
55

66
[deps]
77
Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"

src/UnixTimes.jl

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,24 @@ UnixTime(x::Date) = UnixTime(DateTime(x))
6363
UnixTime(x::Date, y::Time) =
6464
UnixTime(year(x), month(x), day(x), hour(y), minute(y), second(y), millisecond(y), microsecond(y), nanosecond(y))
6565

66+
const DATEFORMAT = dateformat"yyyy-mm-ddTHH:MM:SS.sss"
67+
68+
function UnixTime(s::AbstractString)
69+
try
70+
@assert length(s) == 29
71+
dt = DateTime(chop(s; tail=6), DATEFORMAT)
72+
ns = Nanosecond(parse(Int, last(s, 6)))
73+
UnixTime(dt) + ns
74+
catch
75+
throw(ArgumentError("Invalid UnixTime string"))
76+
end
77+
end
78+
6679
Base.convert(::Type{UnixTime}, x::DateTime) = UnixTime(x)
6780

6881
function Base.show(io::IO, x::UnixTime)
6982
xdt = convert(DateTime, x)
70-
print(io, Dates.format(xdt, dateformat"yyyy-mm-ddTHH:MM:SS.sss"))
83+
print(io, Dates.format(xdt, DATEFORMAT))
7184
v = x.instant.periods.value
7285
d = 100_000
7386
for i in 1:6

test/runtests.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,10 @@ end
4747
@testset "io" begin
4848
x = UnixTime(2020, 1, 2, 3, 4, 5, 6, 7, 8)
4949
@test string(x) == "2020-01-02T03:04:05.006007008"
50+
@test UnixTime(string(x)) == x
51+
@test_throws ArgumentError UnixTime("2025-01-28T15:49:36.5901397023")
52+
@test_throws ArgumentError UnixTime("2025-01-28T15:49:36.59013970")
53+
@test_throws ArgumentError UnixTime(repeat("a", 29))
5054
end
5155

5256
@testset "arithmetic" begin

0 commit comments

Comments
 (0)