javaandroiddate

Regarding current month and year in Android Application


In Android Application, I am trying to retrieve the current month and year, by using the following code.

setMonth(Calendar.getInstance().getTime().getMonth());
setYear(Calendar.getInstance().getTime().getYear());
System.out.println("MONTH sssssssssss:" + Month);
System.out.println("YEAR ssssssssssss:" +  Year);

output is

04-20 16:36:43.723: I/System.out(4718): MONTH sssssssssss:3
04-20 16:36:43.723: I/System.out(4718): YEAR ssssssssssss:114

Could someone please help me to correct year value?


Solution

  • Do the following instead

    Calendar today = Calendar.getInstance();
    int month = today.get(Calendar.MONTH); // january == 0 btw
    int year = today.get(Calendar.YEAR);
    // do your printing here
    

    The reason you are getting 114 is because the getTime() method returns a java.util.Date class, and by default, the java.util.Date class has its year value offset by 1900 (don't ask me why). This means that the current year would be 2014 - 1900 = 114, which is what you are seeing.