如何用Java中的模糊时区解析日期和时间?

时间:2012-11-07 09:33:53

标签: java parsing date time timezone

我正在使用网络服务,对于巴西的弗洛里亚诺波利斯市,我得到以下日期:

2012年11月6日星期二下午5:30 LST

现在时区“LST”给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);

我知道时区很难解析。你有什么建议?

谢谢

2 个答案:

答案 0 :(得分:2)

试试这个

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()));

答案 1 :(得分:0)

我目前的解决方法是:

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