date_time_parser
date_time_parser copied to clipboard
assume date with 4 digits as year
I think that the shorter numbers should be parsed as year and can default to 1 January
iex [11:02 :: 2] > DateTimeParser.parse_date("2022")
{:ok, ~D[1905-07-14]}
Imo it's more likely that it's the current year than 1905.
I understand; however to return a %Date{}
we also need a month and day, so assumptions have to be made. The way to provide these assumptions is via assume_date
:
{:ok, ~D[2022-01-01]} = DateTimeParser.parse_date("2022", assume_date: ~D[0000-01-01])
The above example won't work yet, as you point out, until 4-digit integers are guessed as a year. In your code, you'd want to check if the year is 0000 and consider that an error since that's probably not what you want.
Perhaps if there's a community need, more functions could be made available to parse_year
, parse_day
, parse_month
etc so it's not constrained to the a Date struct.
I'm using this library to parse csv provided by users and there is a lot of weird input going on.
Suprisingly it's handled very well and I just found this somewhere in the logs. (our logic checks then for very old dates - that's how I catched it)
So adding parse_year
would require custom logic to handle this case.