簡體   English   中英

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

[英]How to parse date string using Timezone in GWT

有人在GWT中成功解析了自定義時區的日期字符串嗎? GWT的DateTimeFormat允許根據時區格式化日期,但我沒有找到任何相反操作的方法。 那么,如果我有以下字符串“02:01:2011”(格式“MM:dd:yyyy”),我該怎么辦? 它可以在不同的時區中產生不同的結果。

嘗試更改日期,月份等時會出現另一個問題。如何根據自定義時區執行此操作?

也許有任何庫可以簡化所有這些操作?


我已經解決了問題,並為每個錯過該部分的日期字符串添加了時區部分。 仍在尋找更專業的解決方案。

從服務器向客戶端提供時區(例如,將其包含在日期字符串中)或標准化服務器上​​的時區,以便客戶端可以采用恆定的時區。 如果您在時區中包含日期字符串,則以下代碼段應該有效。

我沒有測試過這個,但是根據文檔,它應該工作:

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

我做了以下操作來解析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);

它在客戶端時區中解析日期,然后將其調整為所需的時區。

最近我傳遞了這個項目: gwt-calendar-class ,它在javascript中模擬Calendar和TimeZone。

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

試試這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM