How to parse date and time with undefined timezone in Java?

I use a web service, and for the city of Florianopolis in Brazil I get the following date:

Tue, 06 Nov 2012 5:30 pm LST

Now the β€œLST” time zone poses a problem for parsing SimpleDateFormat:

// 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 time zones can be hard to make out. What are you offering?

thanks

+4
source share
2 answers

My current workaround:

 // 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); } 
0
source

try it

 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())); 
+2
source

Source: https://habr.com/ru/post/1444545/


All Articles