使用GWT计算减去日期

时间:2015-03-03 04:25:45

标签: java 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周,而且一年也会受到影响。 减去月份和时间的最佳计算方法是什么?年?

1 个答案:

答案 0 :(得分:1)

由于GWT不支持java.util.Calendar,因为其实现所需的复杂性,最终的JS大小等,我将采用基于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)