如何在Smart GWT中获取浏览器真实时区ID及处理夏令时业务
Great question—this is a common pain point when dealing with time zones that have daylight saving time (DST) rules, and relying on fixed-offset Etc/GMT-xx IDs just won't cut it for your Excel upload scenario. Here's how to solve this in Smart GWT:
1. Grab the Real Time Zone ID from the Browser via JSNI
Smart GWT is built on GWT, so we can use GWT's JavaScript Native Interface (JSNI) to tap into the browser's native Intl API—this is the most reliable way to get the actual time zone ID configured on the user's system (like Europe/Rome or America/New_York).
Create a utility class with a JSNI method to fetch the time zone:
public class TimeZoneHelper { // JSNI method to retrieve the browser's real time zone ID public static native String getBrowserRealTimeZoneId() /*-{ // Modern browsers support this API return Intl.DateTimeFormat().resolvedOptions().timeZone; }-*/; }
Then call this method from your Smart GWT client code:
String userTimeZoneId = TimeZoneHelper.getBrowserRealTimeZoneId(); // Send this ID to your backend service for DST processing
2. Fallback for Older Browsers
If you need to support older browsers that don't have the Intl API (rare these days, but possible), you have two solid options:
- Add a manual time zone selector: Populate a dropdown with all valid Java
ZoneIdvalues (you can fetch these on the backend and pass them to the client) and let users pick their time zone. - Use a third-party JS library like
moment-timezoneto detect the time zone, then wrap its detection logic in a JSNI method similar to the example above.
3. Process DST Logic on the Backend
Once you have the real time zone ID, you can use Java's modern date-time API (Java 8+) to handle your Excel records correctly:
- Parse each Excel date-time into a
LocalDateTime(adjust if the Excel dates are in a different format). - Convert it to a
ZonedDateTimeusing the user's real time zone:ZoneId userZone = ZoneId.of(userTimeZoneId); ZonedDateTime zonedDateTime = localExcelDateTime.atZone(userZone); - Check if the date falls within DST for that zone:
boolean isInDST = userZone.getRules().isDaylightSavings(zonedDateTime.toInstant()); - Get the exact offset (including DST if applicable):
ZoneOffset actualOffset = zonedDateTime.getOffset();
This lets you adjust each record's date-time accurately—some records might use DST offset, others won't, depending on when they fall in the year.
Why Etc/GMT-xx Doesn't Work for You
As you noted, getTimezoneOffset() only gives a total offset from UTC, which mixes base zone offset and DST offset into one number. Real time zone IDs (like Europe/Rome) include all the historical and future DST rules for that region, so you can reliably distinguish between fixed offsets and DST-adjusted offsets.
内容的提问来源于stack exchange,提问作者John Wong

