开发者

SimpleDateFormat "Unparseable date" Exception

开发者 https://www.devze.com 2023-04-11 02:44 出处:网络
I am trying to parse datetime string with SimpleDateFormat.parse() but I keep receiving Unparseable date exceptions.

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 to parse: 2011-10-06T12:00:00-08:00

Here is the code I am using:

try {
    String dateStr = "2011-10-06T12:00:00-08:00";
    SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
    SimpleDateFormat dateFormatter = new SimpleDateFormat("MMM d, yyyy");
    Date date = dateParser.parse(dateStr);
    System.out.println(dateFormatter.format(date));         
} catch(Exception e) {
    System.out.println(e.getMessage());
}

Which returns this error: java.text.ParseException: Unparseable date: "2011-10-06T12:00:00-08:00"

As far as I know this is the correct way to use the SimpleDateFormat class but I'm not fluent in 开发者_StackOverflow中文版Java so I could be mistaken. Any one know what my issue is?


The timezone should be GMT-08:00 or -0800 (as Madcore Tom said). See Java docs.

In Java 7 you can use "yyyy-MM-dd'T'HH:mm:ssX"


I believe that SimpleDateFormat will not parse timezones with a colon in them (-08:00). It should be able to parse the date 2011-10-06T12:00:00-0800.

Some simple string manipulation should help you get rid of the colon.


You first need to format the value in "2011-10-06T12: 00: 00-08: 00".

Example: SimpleDateFormat dateParser = new SimpleDateFormat ("yyyy-MM-dd'T'HH: mm: ssZ");

After, create the formating for formataction desired. Ex: SimpleDateFormat fmt = new SimpleDateFormat ("dd / MM / yyyy HH: mm: ss");

and after make parse for date. Ex: Date date = dateParser.parse (dateFormat); and print of date formated.

Below, one complete example.

String dataStr = "2011-10-06T12: 00: 00-08: 00";
SimpleDateFormat dataParser = new SimpleDateFormat ("dd / MM / yyyy HH: mm: ss", Locale.US);
Date date;
Try {
date = dataParser.parse (dataStr);
System.out.println (dateFormatter.format (date));

} cath (ParseException e) {

}


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.


Try with

SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");


For a date format like 2013-06-28T00:00:00+00:00, this code should work:

SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");


I am sure most of you got frustrated from the fact that SimpleDateFormat can not handle ISO8601 format. Here is my little trick to solve this nuisance.

Create a list of Know format you know that you will use for your application and apply SimpleDateFormat to the list. Now, in your formatDate() method, simple try all your known format and trap the Exception, then if still did not have a date, just use

Date d = javax.xml.bind.DatatypeConverter.parseDateTime("2013-06-28T00:00:00+00:00").getTime();
if (d == null)
try {
    SimpleDateFormater ...
}

to try it and see if that work. For more info Simple trick to convert Date format with timezone in Java!


I'd strongly recommend using JodaTime for this sort of thing.

You're trying to parse an ISO Date format, and Joda does that 'out of the box', and will give you plenty of other benefits too.

I long ago gave up trying to get the standard JDK data classes to do helpful things.

0

精彩评论

暂无评论...
验证码 换一张
取 消