如何将日期字符串解析为Date?
如何将下面的日期字符串解析为 Date
对象?
String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("E MM dd kk:mm:ss z yyyy");
Date result = df.parse(target);
抛出异常...
java.text.ParseException: Unparseable date: "Thu Sep 28 20:29:30 JST 2000"
at java.text.DateFormat.parse(DateFormat.java:337)
How do I parse the date string below into a Date
object?
String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("E MM dd kk:mm:ss z yyyy");
Date result = df.parse(target);
Throws exception...
java.text.ParseException: Unparseable date: "Thu Sep 28 20:29:30 JST 2000"
at java.text.DateFormat.parse(DateFormat.java:337)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
模式是错误的。您有一个由 3 个字母组成的日期缩写,因此它必须是
EEE
。您有一个由 3 个字母组成的月份缩写,因此它必须是MMM
。由于这些日期和月份缩写对区域设置敏感,因此您还需要将SimpleDateFormat
区域设置显式指定为英语,否则它将使用平台默认区域设置,而该默认区域设置本身可能不是英语。这里打印的内容
根据我的时区是正确的。
如果您不想使用
HH
而不是kk
,我也会重新考虑。有关有效模式的详细信息,请阅读 javadoc。The pattern is wrong. You have a 3-letter day abbreviation, so it must be
EEE
. You have a 3-letter month abbreviation, so it must beMMM
. As those day and month abbreviations are locale sensitive, you'd like to explicitly specify theSimpleDateFormat
locale to English as well, otherwise it will use the platform default locale which may not be English per se.This prints here
which is correct as per my timezone.
I would also reconsider if you wouldn't rather like to use
HH
instead ofkk
. Read the javadoc for details about valid patterns.这是一个工作示例:
将打印:
Here is a working example:
Will print:
这很好用吗?
This works fine?
并且
仍在运行。但是,如果您的代码抛出异常,那是因为您的工具或 jdk 或任何其他原因。因为我在 IDE 中遇到了同样的错误,但请检查这些 http://ideone.com/Y2cRr< /a> (在线 ide)与 ZZZ 和 Z
输出为:
Thu Sep 28 11:29:30 GMT 2000
and
still runs. However, if your code throws an exception it is because your tool or jdk or any other reason. Because I got same error in my IDE but please check these http://ideone.com/Y2cRr (online ide) with ZZZ and with Z
output is :
Thu Sep 28 11:29:30 GMT 2000
我遇到了这个问题,我将
Locale
设置为US
,然后就可以了。对于
String
“2012 年 7 月 8 日星期日 00:06:30 UTC”
I had this issue, and I set the
Locale
toUS
, then it work.for
String
"Sun Jul 08 00:06:30 UTC 2012"
解析异常是一个已检查的异常,因此在将字符串解析为日期时,必须使用 try-catch 捕获它,正如 @miku 建议的那样......
A parse exception is a checked exception, so you must catch it with a try-catch when working with parsing Strings to Dates, as @miku suggested...