tags:

views:

33

answers:

3

Hello,
I need to get yesterday's date from a Java ME midlet.
I know Java's Calendar object has an add method but Java ME's Calendar doesn't have it.
Is there an easy way to retrive yesterday's date?

Thanks.

+2  A: 

How about something like

Calendar c = Calendar.getInstance();
c.setTimeInMillis(c.getTimeInMillis() - MILLISECONDS_OF_ONE_DAY);

??

aioobe
A: 

Alternatively, something like this:

Calendar c = Calendar.getInstance();
c.set(Calendar.DATE, c.get(Calendar.DATE) - 1);
c.computeTime(); // Make sure getTime returns the updated time

(This code should conform to the CLDC 1.1 Calendar class)

R. Bemrose
Are you sure that won't throw an `ArrayIndexOutOfBoundsException`?
aioobe
Actually, I don't know. I know that the normal Java Calendar class allows negative days and converts them propertly, but the JavaDoc for the CLDC Calendar class doesn't say what it does for those.
R. Bemrose
+1  A: 
    int ny = year, nm =month, nd =day;
    nd-=1;
    if (nd <= 0){
        nd = 31;
        nm-=1;
    }
    if (nm <= 0){
        nm = 12;
        ny-=1;
    }
    Calendar cal = Calendar.getInstance();
    try{
        cal.set(Calendar.YEAR, ny);
        cal.set(Calendar.MONTH,nm);
        cal.set(Calendar.DAY_OF_MONTH,nd);
    }catch(ArrayIndexOutOfBoundsException e){
        nd-=1;
        cal.set(Calendar.YEAR, ny);
        cal.set(Calendar.MONTH,nm);
        cal.set(Calendar.DAY_OF_MONTH,nd);
    }
    return new SimpleDate(cal.getTime());

Calendar will throw exception, if wrong date is specified. By this way we check if the day of month is right.

German
try catch part shall be in loop!february!
German