如何在 Java 中使用 DateFormat 解析月份完整形式的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2219139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse month full form string using DateFormat in Java?
提问by tommy chheng
I tried this:
我试过这个:
DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy");
Date d = fmt.parse("June 27, 2007");
error:
错误:
Exception in thread "main" java.text.ParseException: Unparseable date: "June 27, 2007"
Exception in thread "main" java.text.ParseException: Unparseable date: "June 27, 2007"
The java docs say I should use four characters to match the full form. I'm only able to use MMMsuccessfully with abbreviated months like "Jun"but i need to match full form.
java 文档说我应该使用四个字符来匹配完整的表单。我只能成功地使用像“Jun”这样的缩写月份的MMM,但我需要匹配完整的形式。
Text: For formatting, if the number of pattern letters is 4 or more, the full form is used; otherwise a short or abbreviated form is used if available. For parsing, both forms are accepted, independent of the number of pattern letters.
文本:对于格式,如果模式字母的数量为 4 个或更多,则使用完整形式;否则,如果可用,则使用简短或缩写形式。对于解析,两种形式都被接受,与模式字母的数量无关。
https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
采纳答案by Mark Byers
You are probably using a locale where the month names are not "January", "February", etc. but some other words in your local language.
您可能使用的语言环境中月份名称不是“一月”、“二月”等,而是您当地语言中的其他一些词。
Try specifying the locale you wish to use, for example Locale.US
:
尝试指定您要使用的语言环境,例如Locale.US
:
DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
Date d = fmt.parse("June 27, 2007");
Also, you have an extra space in the date string, but actually this has no effect on the result. It works either way.
此外,日期字符串中有一个额外的空格,但实际上这对结果没有影响。无论哪种方式都有效。
回答by gkephorus
Just to top this up to the new Java 8 API:
只是为了补充新的 Java 8 API:
DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("MMMM dd, yyyy").toFormatter();
TemporalAccessor ta = formatter.parse("June 27, 2007");
Instant instant = LocalDate.from(ta).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date d = Date.from(instant);
assertThat(d.getYear(), is(107));
assertThat(d.getMonth(), is(5));
A bit more verbose but you also see that the methods of Date used are deprecated ;-) Time to move on.
有点冗长,但您也看到不推荐使用 Date 的方法;-) 是时候继续前进了。
回答by Aresan
val currentTime = Calendar.getInstance().time
SimpleDateFormat("MMMM", Locale.getDefault()).format(date.time)