I'm trying to use joda-time to parse a date string of the form YYYY-MM-DD
. I have test code like this:
DateTimeFormatter dateDecoder = DateTimeFormat.forPattern("YYYY-MM-DD");
DateTime dateTime = dateDecoder.parseDateTime("2005-07-30");
System.out.println(dateTime);
Which outputs:
2005-01-30T00:00:00.000Z
As you can see, the DateTime
object produced is 30 Jan 2005
, instead of 30 July 2005
.
Appreciate any help. I just assumed this would work because it's one of the date formats listed here.
The confusion is with what the ISO format actually is. YYYY-MM-DD
is not the ISO format, the actual resulting date is.
So 2005-07-30
is in ISO-8601 format, and the spec uses YYYY-MM-DD
to describe the format. There is no connection between the use of YYYY-MM-DD
as a pattern in the spec and any piece of code. The only constraint the spec places is that the result consists of a 4 digit year folowed by a dash followed by a 2 digit month followed by a dash followed by a two digit day-of-month.
As such, the spec could have used $year4-$month2-$day2
, which would equally well define the output format.
You will need to search and replace any input pattern to convert "Y" to "y" and "D" to "d".
I've also added some enhanced documentation of formatting.
You're answer is in the docs: http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html
The string format should be something like: "yyyy-MM-dd".
The date format described in the w3 document and JodaTime's DateTimeFormat
are different.
More specifically, in DateTimeFormat
, the pattern DD
is for Day in year
, so the value for DD
of 30
is the 30th day in the year, ie. January 30th. As the formatter is reading your date String
, it sets the month to 07
. When it reads the day of year, it will overwrite that with 01
for January.
You need to use the pattern strings expected by DateTimeFormat
, not the ones expected by the w3 dat and time formats. In this case, that would be
DateTimeFormatter dateDecoder = DateTimeFormat.forPattern("yyyy-MM-dd");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With