如何使用 Java 中的 DateFormat 解析月份完整形式字符串?
我尝试了这个:
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"
java 文档说我应该使用四个字符来匹配完整的形式。 我只能成功使用 MMM 和诸如 “Jun” 之类的缩写月份,但我需要匹配完整形式。
文本:用于格式化,如果数字 模式字母为 4 个或更多,则 使用完整形式;否则短路 或使用缩写形式,如果 可用的。对于解析来说,两种形式都是 接受,与数量无关 模式字母。
https://docs.oracle.com/javase/6 /docs/api/java/text/SimpleDateFormat.html
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"
The java docs say I should use four characters to match the full form.
I'm only able to use MMM successfully with abbreviated months like "Jun" but i need to match full form.
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.
https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能使用的语言环境中月份名称不是“一月”、“二月”等,而是您当地语言中的其他单词。
尝试指定您希望使用的区域设置,例如
Locale.US
:此外,日期字符串中有一个额外的空格,但实际上这对结果没有影响。无论哪种方式都有效。
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
:Also, you have an extra space in the date string, but actually this has no effect on the result. It works either way.
java.time 中的 LocalDate
使用 java.time(现代 Java 日期和时间 API)中的
LocalDate
来获取日期输出:
正如其他人已经说过的,当您的字符串是英语时,请记住指定英语区域设置。
LocalDate
是没有时间的日期,因此比旧的Date
类更适合字符串中的日期。尽管名称如此,Date
并不代表日期,而是代表世界不同时区至少两个不同日期的时间点。仅当您需要一个老式的
Date
API,而您现在无法升级到 java.time 时,请像这样转换:在我的时区中输出:
链接
Oracle 教程:日期时间 解释如何操作使用java.time。
LocalDate from java.time
Use
LocalDate
from java.time, the modern Java date and time API, for a dateOutput:
As others have said already, remember to specify an English-speaking locale when your string is in English. A
LocalDate
is a date without time of day, so a lot better suitable for the date from your string than the oldDate
class. Despite its name aDate
does not represent a date but a point in time that falls on at least two different dates in different time zones of the world.Only if you need an old-fashioned
Date
for an API that you cannot afford to upgrade to java.time just now, convert like this:Output in my time zone:
Link
Oracle tutorial: Date Time explaining how to use java.time.
补充一下新的 Java 8 API:
有点冗长,但您也会看到所使用的 Date 方法已被弃用;-) 是时候继续了。
Just to top this up to the new Java 8 API:
A bit more verbose but you also see that the methods of Date used are deprecated ;-) Time to move on.