简体   繁体   中英

How to parse a date and time with an ambiguous timezone in Java?

I am using a web service and for the city Florianopolis in Brazil I get the following date:

Tue, 06 Nov 2012 5:30 pm LST

Now the timezone "LST" creates a problem to the SimpleDateFormat parser:

// Date to parse
String dateString = "Tue, 06 Nov 2012 5:30 pm LST";

// This parser works with other timezones
SimpleDateFormat LONG_DATE = new SimpleDateFormat("EEE, d MMM yyyy h:mm a zzz");

// Here it throws a ParseException
Date date = LONG_DATE.parse(dateString);

I know that the timezones can be difficult to parse. What do you propose?

Thank you

Try this

DateFormat gmtFormat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");

TimeZone gmtTime = TimeZone.getTimeZone("GMT-02:00");
gmtFormat.setTimeZone(gmtTime);

System.out.println("Brazil :: " + gmtFormat.format(new Date()));

My current workaround is:

// Date to parse
String dateString = "Tue, 06 Nov 2012 5:30 pm LST";

// This parser works with some timezones but fails with ambiguous ones...
DateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy h:mm a zzz");

Date date = null;  
try {
    // Try to parse normally
    date = dateFormat.parse(dateString);
} catch (ParseException e) {
    // Failed, try to parse with a GMT timezone as a workaround.
    // Replace the last 3 characters with "GMT"
    dateString = dateString.replaceFirst("...$", "GMT");
    // Parse again
    date = dateFormat.parse(dateString);
}

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