clojure.java-time icon indicating copy to clipboard operation
clojure.java-time copied to clipboard

Inconsistency in parsing data with local-date

Open elisehuard opened this issue 8 years ago • 2 comments

I want to process a timeseries with monthly labels, so something like "2012-10" etc, but parser seems unhappy with this. I understand why, but it's pretty impractical.

user> (local-date-time "MM/yyyy" "09/2015")                                                       
DateTimeException Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=9, Year=2015},IS\
O of type java.time.format.Parsed  java.time.LocalDate.from (LocalDate.java:368)                  
user> (local-date 2015 10)                                                                        
#object[java.time.LocalDate 0x6a08b281 "2015-10-01"

elisehuard avatar Aug 16 '17 15:08 elisehuard

Sadly, this library doesn't do much outside of what is provided by the java.time API. This is the limitation of the DateTimeFormatter:

boot.user=> (java.time.LocalDate/parse "2017/05" (java.time.format.DateTimeFormatter/ofPattern "yyyy/MM"))

            java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {Year=2017, MonthOfYear=5},ISO of type java.time.format.Parsed
java.time.format.DateTimeParseException: Text '2017/05' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {Year=2017, MonthOfYear=5},ISO of type java.time.format.Parsed

I can only recommend something like:

(defn month-year->local-date-time [^String str]
  (->> (.split str "\\/") (map #(Integer/parseInt %)) (reverse) (apply j/local-date-time)))

dm3 avatar Aug 16 '17 18:08 dm3

I can imagine a feature that would harmonize the Number* -> TemporalEntity constructors with their parse counterparts. It should require a dynamic context set up before parsing, or a special kind of formatter used so that the default (strict) behaviour is preserved.

There's a DateTimeFormatter#parseUnresolved which can be used to obtain a parsed TemporalAccessor which then needs to be resolved manually. However, there doesn't seem to be an easy way to just throw more default fields into the parse result and resolve it.

If anyone wants to tackle this - I'd be happy to collaborate :)

dm3 avatar Aug 18 '17 09:08 dm3