I want to test if a string is in a date format and parse it.
Becaus try … catch need a lot of time I use tryparse().
But I need a normal date, no nullable date. At the moment I do It like this:
datenullable = tryparse(Dates.Date, "2017-01-15")
if !isnull(datenullable)
parse(Dates.Date, "2017-01-15")
else
println("no match return/do something else")
end
Is there a better way?
I was not aware of a tryparse
method for dates, but in any case, see get
for accessing the value inside the Nullable
. You can also provide a default as the second argument.
Thank you - get()
works. I think tryparse()
for dates is new in Julia 0.6. The following function returns the parsed date
, or 0000-01-01
if parse fails, it is fast in both cases:
function parsedate(ds, df)
datenullable = tryparse(Dates.Date, ds, df)
if isnull(datenullable)
return Date(0)
else
return get(datenullable)
end
end
ds = "12.12.2017"
df = DateFormat("dd.mm.yyyy")
parsedate(ds, dfs)
2017-12-12
parsedate(ds, df) = get(tryparse(Dates.Date, ds, df), Date(0))
makes use of the optional second argument for get
, and looks a bit better because of that. Might also be a bit faster, but I didn’t check.