2015-03-03 53 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)