SimpleDateFormat “Unparseable date” Exception

后端 未结 8 1728
再見小時候
再見小時候 2020-12-20 16:55

I am trying to parse datetime string with SimpleDateFormat.parse() but I keep receiving Unparseable date exceptions.

Here is the date format I am trying

8条回答
  •  囚心锁ツ
    2020-12-20 17:52

    tl;dr

    OffsetDateTime.parse( "2011-10-06T12:00:00-08:00" ) 
        .format( 
            DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( Locale.US )  // Or Locale.CANADA_FRENCH and such.
        )
    

    Oct 6, 2011

    java.time

    The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes.

    You input string is in a format that complies with the ISO 8106 standard. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

    Parse as an OffsetDateTime because your input strings includes an offset-from-UTC but not a time zone.

    OffsetDateTime odt = OffsetDateTime.parse( "2011-10-06T12:00:00-08:00" ) ;
    

    odt.toString(): 2011-10-06T12:00-08:00

    Generate a string in your desired format. Let java.time automatically localize rather than hard-code formatting patterns.

    DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( Locale.US );  // Or Locale.CANADA_FRENCH and such.
    String output = odt.format( f );
    

    output: Oct 6, 2011

    When seralizing a date-time value as text, use the standard ISO 8601 formats rather than a localized format.

    String output = odt.toLocalDate().toString() ;
    

    2011-10-06


    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

    Where to obtain the java.time classes?

    • Java SE 8, Java SE 9, and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • Later versions of Android bundle implementations of the java.time classes.
      • For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

提交回复
热议问题