如何在GWT中使用Timezone解析日期字符串

时间:2011-02-24 13:00:30

标签: java javascript gwt date timezone

是否有人在GWT中使用自定义时区成功解析日期字符串? GWT的DateTimeFormat允许根据时区格式化日期,但我没有找到任何相反操作的方法。那么,如果我有以下字符串“02:01:2011”(格式“MM:dd:yyyy”),我该怎么办?它可以在不同的时区产生不同的结果。

尝试更改日期,月份等时会出现另一个问题。如何根据自定义时区执行此操作?

也许有任何库可以简化所有这些操作?


我已经解决了问题,并为每个错过该部分的日期字符串添加了时区部分。仍在寻找更专业的解决方案。

4 个答案:

答案 0 :(得分:5)

从服务器向客户端提供时区(例如,将其包含在日期字符串中)或标准化服务器上​​的时区,以便客户端可以采用恒定的时区。如果您将时区包含在日期字符串中,则以下代码段应该有效。

我没有对此进行测试,但根据文档,它应该有效:

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

根据您表示时区的方式,您可以更改格式字符串(Z)中的最终变量。有关详细信息,请参阅文档:http://google-web-toolkit.googlecode.com/svn/javadoc/latest/com/google/gwt/i18n/client/DateTimeFormat.html

答案 1 :(得分:3)

我做了以下操作来解析TimeZone tz中的日期。 它可能很狡猾,但它确实有效: -

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

它解析客户端时区中的日期,然后将其调整为所需的时区。

答案 2 :(得分:1)

最近我传递了这个项目:gwt-calendar-class,它在javascript中模拟了Calendar和TimeZone。

答案 3 :(得分:-3)

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

试试这个