Amira Elsayed Ismail
Amira Elsayed Ismail

Reputation: 9394

get previous date in J2ME

I want to get the date of previous month in J2ME.

I have found this code :

Calendar c = Calendar.getInstance();  
c.add(Calendar.YEAR, -1); //one year back  
c.add(Calendar.MONTH, -1);// then one month  

but this is working in Java SE not J2ME, please if anyone can help me find the corresponding method or class in J2ME?

Upvotes: 0

Views: 218

Answers (1)

Yaroslav Mytkalyk
Yaroslav Mytkalyk

Reputation: 17105

Calendar does not have method add.

    c.set(Calendar.MONTH, -1)

Means you set value -1 at field MONTH. Your solution is

    // get current month
    int m = c.get(Calendar.MONTH);
    // decrement it
    if (--m < 0) {
        // if was january, must become december of past year
        m = 11;
        // set year to previous
        c.set(Calendar.YEAR, c.get(Calendar.YEAR) - 1);
    }
    // set new value "m" to field MONTH
    c.set(Calendar.MONTH, m);

Please refer to http://docs.oracle.com/javame/config/cldc/ref-impl/midp2.0/jsr118/index.html for documentation. You should't work without it unless you know all you need.

Upvotes: 5

Related Questions