简体   繁体   English

用GWT计算减日期

[英]Minus date calculation with GWT

Here is my try to do date minus for 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));
}

The problem I see here is with the calculation in terms of month and year. 我在这里看到的问题是关于月份和年份的计算。 As months is not always 4-week aligned and a year is also affected. 由于月份并非总是4周对齐,因此一年也会受到影响。 What could be the best calculation for subtracting month & year? 减去月份和年份的最佳计算方法是什么?

Since java.util.Calendar is unsupported in GWT because of the complexity needed for its implementation, the final JS size, etc, I would go with a simple and lightweight solution based on JS. 由于GWT不支持java.util.Calendar ,因为其实现所需的复杂性,最终的JS大小等,我将选择一个基于JS的简单轻巧的解决方案。

Apart from the java Date implementation, in GWT we have the JsDate wrapper which includes all the methods available in the native JS date, so subtracting a month or a year should be as simpler as: 除了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()); 

You can do the same to manipulate other units: 您可以执行相同操作来操纵其他单元:

    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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM