Minus date calculation with GWT

quarks

Here is my try to do date minus for 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. What could be the best calculation for subtracting month & year?

Manolo Carrasco Moñino

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.

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:

    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)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related