使用 GWT 计算减去日期

Minus date calculation with 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 周对齐,因此一年也会受到影响。 减去月份和年份的最佳计算方法是什么?

由于 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)