如何用XMLGregorianCalendar处理CST/CDT互转?WAS夏令时转换异常求助
I’ve run into similar timezone-related quirks with older WebSphere versions, so I know exactly where this is coming from.
Why this happens
WAS7 typically runs on JDK 6, while WAS8.5 uses JDK 7 or later. The key issue here is the outdated timezone data (tzdata) in JDK 6, or differences in how older JDKs handle DST transitions. When you call the no-argument toGregorianCalendar() method, it relies on the JVM’s default timezone settings. For the 2018 CST→CDT switch on March 11, JDK 6 might not correctly apply the DST offset, leading to the wrong local time calculation.
Your input is 2018-03-11T05:00:00 (UTC-5), which should map to Sun Mar 11 00:00:00 CDT 2018 (since CDT is UTC-5). But WAS7’s JDK is incorrectly applying the CST offset (UTC-6) here, shifting the time back to March 10th at midnight.
How to fix it
The solution is to explicitly control the timezone during conversion instead of relying on defaults. Modify your conversion method to use the overloaded toGregorianCalendar() that lets you specify the target timezone, ensuring the correct DST rules are applied.
Here’s the updated code:
import java.util.Date; import java.util.TimeZone; import java.util.Locale; import javax.xml.datatype.XMLGregorianCalendar; /** Converts XMLGregorianCalendar to java.util.Date */ public static Date toDate(XMLGregorianCalendar calendar) { if (calendar == null) { return null; } // Specify the exact timezone for CST/CDT (America/Chicago covers this) TimeZone targetTz = TimeZone.getTimeZone("America/Chicago"); // Use the overloaded method to enforce the timezone during conversion return calendar.toGregorianCalendar(targetTz, Locale.getDefault(), null).getTime(); }
Bonus tips
- Update JDK timezone data: If you can’t modify the code, try updating the tzdata files in your WAS7 JDK to include the latest DST rules. This ensures older JDKs recognize newer DST transition dates.
- Validate input timezone: Double-check that your input XMLGregorianCalendar has the correct timezone offset specified. If the XML time doesn’t include timezone info, make sure you’re parsing it with the right timezone from the start.
内容的提问来源于stack exchange,提问作者jcrshankar

