简体   繁体   中英

SimpleDateFormat parse

I have an issue with SimpleDateFormat:

Error:

Unparseable date: "Thu, 09 Nov 2017 16:17:42 GMT"

Code:

DF_SERVER_FORMAT="EEE, dd MMM yyyy HH:mm:ss'Z'"
....
var formater=SimpleDateFormat(DF_SERVER_FORMAT)
formater.parse(source)

as per SimpleDateFormat documentation , Z (capitalized) is for an RFC 822 time zone , eg -0800

for a General time zone use z .

this should work:

DF_SERVER_FORMAT="EEE, dd MMM yyyy HH:mm:ss z"

尝试"EEE, d MMM yyyy HH:mm:ss z"该模式对我有用。

You can try to format some date using your pattern, to see the difference and then fix your pattern accordingly. Here is what I did in J2SE:

SimpleDateFormat df = new SimpleDateFormat("EEE dd MMM yyyy HH:mm:ss'Z'");
System.out.println(df.format(new Date()));

This is producing:

Thu 09 Nov 2017 17:49:07Z

But, when I used the pattern " EEE, dd MMM yyyy HH:mm:ss z ", it produced the expected result:

Thu, 09 Nov 2017 17:51:09 CET

For anyone who either is fine with an external dependency (temporarily) or is using Java 8 or later I wanted to contribute the modern answer. Because I consider SimpleDateFormat long outdated.

The modern Java date and time API is generally much nicer to work with. In addition, your string is in RFC 1123 format, and the modern API comes with a formatter for this format. So no need to build your format pattern string yourself (my code is pure Java, I trust you to adopt to Kotlin):

    String dateString = "Thu, 09 Nov 2017 16:17:42 GMT";
    OffsetDateTime dateTime = OffsetDateTime.parse(dateString, 
            DateTimeFormatter.RFC_1123_DATE_TIME);

This produces an OffsetDateTime of 2017-11-09T16:17:42Z as expected.

To use this on Android, get ThreeTenABP , see this question: How to use ThreeTenABP in Android Project . Java 8 and later come with the modern API built-in. If using Java 6 or 7 on non-Android, you need the ThreeTen Backport .

What went wrong in your code? With your format pattern string you were asking for a literal Z right after the seconds, with no space in between. Since your input string didn't have a Z there, parsing failed (instead it had a space and the offset ID GMT ). In addition, your code seems to be sensitive to locale: if your default locale is one where the abbreviation for Thursday is not Thu or for November not Nov, parsing will fail (in contrast, RFC_1123_DATE_TIME expects (and requires) day and month abbreviations in English independently of locale).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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