Java SimpleDatetime parse

你说的曾经没有我的故事 提交于 2019-12-12 02:07:02

问题


Maybe i'm just missing the obvious, but I can't get SimpleDateTimes parse() method to work:

I want to parse dates like June 19, 2011. So, according to the documentation: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

for my needs it should be:

  • M: Month in year. If the number of pattern letters is 3 or more, the month is interpreted as text; --> MMM
  • d: Day in month. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields --> d
  • y: Year. For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits. --> yyyy

but with

SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy");
Date d = sdf.parse("June 19, 2011");

I'll always get java.text.ParseException: Unparseable date: "June 19, 2011"

Where am I thinking wrong? :)


回答1:


I'm assuming your Locale is some German value since you seem to be in Germany. June won't parse as a German word for a month. Set your Locale to an English value.

SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy", Locale.ENGLISH);



回答2:


Joda-Time

Here is an example akin to the correct answer but using the Joda-Time library.

Both Joda-Time and the java.time package are far superior to the old java.util.Date an .Calendar classes bundled with Java. One of many advantages is a class, LocalDate, to represent date-only values without time-of-day or time zone.

DateTimeFormatter formatter = DateTimeFormat.forPattern( "MMM, d, YYYY" ).withLocale( Locale.ENGLISH );
LocalDate localDate = formatter.parseLocalDate( "June 19, 2011" );


来源:https://stackoverflow.com/questions/26076595/java-simpledatetime-parse

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