Has anybody succeeded parsing date string with a custom timezone in GWT? GWT's DateTimeFormat allows to format dates based on time z开发者_高级运维one, but I haven't found any method for doing opposite operation. So what should I do if I have following string "02:01:2011" (format "MM:dd:yyyy"). It can have different results in different timezones.
The other problem appears when trying to change dates, months and etc. How can I do it based on a custom timezone?
Maybe there is any library which can simplify all these operations?
I have made workaround and add timezone part to each date string which miss that part. Still looking for a more professional solution.
Either give the timezone to the client from the server (e.g., include it in the date string) or standardize the timezone on the server so that the client can assume a constant timezone. If you include the timezone with the date string, the below code snippet should work.
I havent tested this, but according to the docs, it should work:
String dateStr = "04/21/2011 01:37:36 -0800;
DateTimeFormat format = new DateTimeFormat("MM/dd/yyyy HH:mm:ss Z");
Date date = format.parse(dateStr);
Depending on how you are representing the timezone, you can change the final variable in the format string (the Z). See the docs for details: http://google-web-toolkit.googlecode.com/svn/javadoc/latest/com/google/gwt/i18n/client/DateTimeFormat.html
I did the following to parse a date in the TimeZone tz. It's probably dodgy, but it works: -
final long MILLIS_IN_MINUTE = 60000;
Date localDate = DateTimeFormat.getFormat("dd MMM yyyy HH:mm:ss").parse(dateString);
int localOffset = localDate.getTimezoneOffset() * MILLIS_IN_MINUTE;
int targetOffset = tz.getOffset(localDate) * MILLIS_IN_MINUTE;
// Subtract the offset to make this into a UTC date.
return new Date(localDate.getTime() - localOffset + targetOffset);
It parses the date in the client timezone and then adjusts it to the required timezone.
Recently I passed upon this project: gwt-calendar-class which emulates Calendar and TimeZone in javascript.
public static Date getDateGWT(final String strDate, final int style) {
Date date = null;
int useStyle = style;
if (!validStyle(style)) {
useStyle = DEFAULT_DATE_STYLE;
}
if ((strDate != null) && (strDate.trim().length() > 0)) {
DateTimeFormat df = getDateFormatGWT(useStyle);
try {
date = df.parse(strDate);
} catch (Exception e) {
date = df.parse(date.toString());
}
}
return date;
}
private static DateTimeFormat getDateTimeFormatGWT(final int style) {
switch(style) {
case SHORT:
return DateTimeFormat.getShortDateTimeFormat();
case MEDIUM:
return DateTimeFormat.getMediumDateTimeFormat();
case LONG:
return DateTimeFormat.getLongDateTimeFormat();
case FULL:
return DateTimeFormat.getFullDateTimeFormat();
default :
return DateTimeFormat.getMediumDateTimeFormat();
}
}
Try This
精彩评论