There's a somewhat subtle bug-ish issue with using LocalDate.parse()
or new LocalDate()
. A code snippet is worth a thousand words. In the following example in the scala repl I wanted to get a Local date in a string format yyyyMMdd. LocalDate.parse()
is happy to give me an instance of a LocalDate, but it's not the correct one (new LocalDate()
has the same behavior):
scala> org.joda.time.LocalDate.parse("20120202")
res3: org.joda.time.LocalDate = 20120202-01-01
I give it Feb 2, 2016 in the format yyyyMMdd and I get back a date of January 1, 20120202. I'm going out on a limb here: I don't think that this is what it should be doing. Joda uses 'yyyy-MM-dd' as the default but implicitly will accept a string with no '-' characters, thinking you want January 1 of that year? That does not seem like a reasonable default behavior to me.
Given this, it seems to me that using a joda date formatter that can't be so easily fooled is a better solution to parsing a string. Moreover, LocalDate.parse()
should probably throw an exception if the date format is not 'yyyy-MM-dd':
scala> val format = org.joda.time.format.DateTimeFormat.forPattern("yyyyMMdd")
format: org.joda.time.format.DateTimeFormatter = org.joda.time.format.DateTimeFormatter@56826a75
scala> org.joda.time.LocalDate.parse("20120202", format)
res4: org.joda.time.LocalDate = 2012-02-02
this will cause other formats to fail so you don't get this odd buggy behavior:
scala> val format = org.joda.time.format.DateTimeFormat.forPattern("yyyy-MM-dd")
format: org.joda.time.format.DateTimeFormatter = org.joda.time.format.DateTimeFormatter@781aff8b
scala> org.joda.time.LocalDate.parse("20120202", format)
java.lang.IllegalArgumentException: Invalid format: "20120202" is too short
at org.joda.time.format.DateTimeFormatter.parseLocalDateTime(DateTimeFormatter.java:900)
at org.joda.time.format.DateTimeFormatter.parseLocalDate(DateTimeFormatter.java:844)
at org.joda.time.LocalDate.parse(LocalDate.java:179)
... 65 elided
which is a much more sane behavior than returning a date in the year 20120202.