How do I parse “YYYY-MM-DD” with joda time

ぃ、小莉子 提交于 2021-02-07 14:27:34

问题


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.


回答1:


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.




回答2:


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".




回答3:


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");


来源:https://stackoverflow.com/questions/19166186/how-do-i-parse-yyyy-mm-dd-with-joda-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!