2015-03-03 55 views
0

這是我嘗試做日期減去了GWT:負日期計算與GWT

Date from = new Date(); 
Date to = new Date(); 

    if(filter.equals(DATE_FILTER.PAST_HOUR)){ 
     minusHoursToDate(to, 1); 
    } else if(filter.equals(DATE_FILTER.PAST_24_HOURS)){ 
     minusHoursToDate(to, 1 * 24); 
    } else if(filter.equals(DATE_FILTER.PAST_WEEK)){ 
     minusHoursToDate(to, 1 * 24 * 7); 
    } else if(filter.equals(DATE_FILTER.PAST_MONTH)){ 
     minusHoursToDate(to, 1 * 24 * 7 * 4); 
    } else if(filter.equals(DATE_FILTER.PAST_YEAR)){ 
     minusHoursToDate(to, 1 * 24 * 7 * 4 * 12); 
    } 

public static void minusHoursToDate(Date date, int hours){ 
    date.setTime(date.getTime() - (hours * 3600000)); 
} 

我看到這裏的問題是,在一個月和一年的規定計算。由於月份並不總是4週一致,並且一年也受到影響。 減去月份&年的最佳計算是什麼?

+0

如何關注GWT? – Cataclysm 2015-03-03 04:28:32

+0

我認爲你的錯誤是使用相同的對象。在更新對象一次後,下次計算將通過上次更新的結果生效。並檢查使用靜態方法。 – Cataclysm 2015-03-03 04:36:10

回答

1

由於java.util.Calendar由於其實現所需的複雜性,最終的JS大小等因素,在GWT中不受支持,所以我將使用基於JS的簡單輕量級解決方案。

從Java Date實施

除此之外,在GWT我們有JsDate包裝,其中包括所有在本地JS日期可用的方法,所以減去一個月或一年應儘量簡單,因爲:

int months = -2; 
    int years = -3; 
    JsDate j = JsDate.create(new Date().getTime()); 
    j.setMonth(j.getMonth() + months); 
    j.setFullYear(j.getFullYear() + years); 
    Date d = new Date((long)j.getTime()); 

你也可以這樣操作其他單元:

getDate() Returns the day of the month (from 1-31) 
    getDay() Returns the day of the week (from 0-6) 
    getFullYear() Returns the year (four digits) 
    getHours() Returns the hour (from 0-23) 
    getMilliseconds() Returns the milliseconds (from 0-999) 
    getMinutes() Returns the minutes (from 0-59) 
    getMonth() Returns the month (from 0-11) 
    getSeconds() Returns the seconds (from 0-59)