Nimrod Shory
Nimrod Shory

Reputation: 2505

Java ME get yesterday's date

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.

Upvotes: 1

Views: 523

Answers (3)

German
German

Reputation: 11

    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.

Upvotes: 1

Powerlord
Powerlord

Reputation: 88786

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)

Upvotes: 1

aioobe
aioobe

Reputation: 420951

How about something like

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

??

Upvotes: 3

Related Questions