Crystal: Time.parse_iso8601 doesn't work without time as well as date

Created on 31 Aug 2020  路  6Comments  路  Source: crystal-lang/crystal

When given a datestring with no attached time (eg., 2020-08-31), Time.parse_iso8601 fails with a cryptic error about a trailing >>. Specifically:

Exception: Invalid number at 10: "2020-08-31>>" (Time::Format::Error)

This can be shown here. It would be nice to have it parse the date and have a default time, or at least have a less cryptic error.

topictime

Most helpful comment

Still, a less cryptic error method could be helpful.

All 6 comments

I think this is more so just an issue of .parse_iso8601 not allowing for date only strings (as opposed to datetime strings).

https://carc.in/#/r/9m3n

pp Time.parse_iso8601 "2020-08-31T15:40:55+00:00" # => 2020-08-31 15:40:55.0 +00:00
pp Time.parse_iso8601 "2020-08-31" # => Unhandled exception: Invalid number at 10: "2020-08-31>>" (Time::Format::Error)

YAML side of this is just a red herring.

@sugarfi Could probably just use https://crystal-lang.org/api/Time.html#parse_utc(time:String,pattern:String):Time-class-method or the parse_local variant in this case.

@Blacksmoke16 thanks! I've updated the post to be more relevant to the issue.

I would say this is expected behavior as parse_iso8601 method documentation states Parse datetime format specified by ISO 8601., so it is expecting a datetime string instead of string with date only.

For parsing ISO 8601 date you can do sth like

pp Time::Format::ISO_8601_DATE.parse("2020-08-31") # => 2020-08-31 00:00:00.0 UTC

Still, a less cryptic error method could be helpful.

We could improve the implementation of parse_iso8601 to automatically parse date or datetime depending on the input. Then Time.parse_iso8601 "2020-08-31" would work. But it's more fuzzy that way. You can't tell wether the string was a date or a date time because both just return a Time instance. However, for more strict use cases, you could rely on Time::Format::ISO_8601_DATE.parse and Time::Format::ISO_8601_DATE_TIME.parse. So it might actually be a good idea to make this more flexible. WDYT?

And I totally agree that the error messages for parser errors are probably not very helpful if you don't know the details of the implementation.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lgphp picture lgphp  路  3Comments

costajob picture costajob  路  3Comments

asterite picture asterite  路  3Comments

jhass picture jhass  路  3Comments

asterite picture asterite  路  3Comments