简体   繁体   English

为什么这个 SimpleDateFormat 不能解析这个日期字符串?

[英]Why can't this SimpleDateFormat parse this date string?

The SimpleDateFormat:简单日期格式:

SimpleDateFormat pdf = new SimpleDateFormat("MM dd yyyy hh:mm:ss:SSSaa");

The exception thrown by pdf.parse("Mar 30 2010 5:27:40:140PM"); pdf.parse("Mar 30 2010 5:27:40:140PM");抛出的异常pdf.parse("Mar 30 2010 5:27:40:140PM"); :

java.text.ParseException: Unparseable date: "Mar 30 2010 5:27:40:140PM"

Any ideas?有任何想法吗?


Edit: thanks for the fast answers.编辑:感谢您的快速回答。 You were all correct, I just missed that one key sentence in the SimpleDateFormat docs - I should probably call it a day.你们都是对的,我只是错过了 SimpleDateFormat 文档中的一个关键句子——我可能应该收工了。

First, three-char months are to be represented by MMM .首先,三个字符的月份将由MMM表示。 Second, one-two digit hours are to be represented by h .其次,一位两位数的小时由h表示。 Third, Mar seems to be English, you'll need to supply a Locale.ENGLISH , else it won't work properly in machines with a different default locale.第三, Mar似乎是英语,您需要提供Locale.ENGLISH ,否则它将无法在具有不同默认语言环境的机器中正常工作。

The following works:以下工作:

SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy h:mm:ss:SSSa", Locale.ENGLISH);
System.out.println(sdf.parse("Mar 30 2010 5:27:40:140PM"));

Result (I'm at GMT-4 w/o DST):结果(我在 GMT-4,没有 DST):

Tue Mar 30 17:27:40 BOT 2010

Also see the java.text.SimpleDateFormat javadoc .另请参阅java.text.SimpleDateFormat javadoc

Why you called it pdf is beyond me, so I renamed it sdf ;)为什么你称它为pdf超出我的sdf ,所以我将它重命名为sdf ;)

From SimpleDateFormat javadocs :SimpleDateFormat javadocs

Month: If the number of pattern letters is 3 or more, the month is interpreted as text;月份:如果模式字母的数量为 3 个或更多,则将月份解释为文本; otherwise, it is interpreted as a number.否则,它被解释为一个数字。

Try to use pattern like "MMM dd yyyy"尝试使用像“MMM dd yyyy”这样的模式

MM stands for numeric month. MM 代表数字月份。 Use MMM.使用 MMM。

java.time时间

I am providing the modern answer.我正在提供现代答案。 The other answers are correct, but the SimpleDateFormat class that you used is notoriously troublesome and long outdated.其他答案是正确的,但您使用的SimpleDateFormat类是出了名的麻烦且已过时。 Instead I am using java.time, the modern and superior Java date and time API.相反,我使用的是 java.time,现代和高级的 Java 日期和时间 API。

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
            "MMM d uuuu h:mm:ss:SSSa", Locale.ROOT);
    String dateTimeString = "Mar 30 2010 5:27:40:140PM";
    LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
    System.out.println(dateTime);

Output:输出:

2010-03-30T17:27:40.140 2010-03-30T17:27:40.140

Link: Oracle tutorial: Date Time explaining how to use java.time.链接: Oracle 教程:解释如何使用 java.time 的日期时间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM