Skip to content
Advertisement

How to get last month/year in java?

How do I find out the last month and its year in Java?

e.g. If today is Oct. 10 2012, the result should be Month = 9 and Year = 2012. If today is Jan. 10 2013, the result should be Month = 12 and Year = 2012.

Advertisement

Answer

Your solution is here but instead of addition you need to use subtraction

c.add(Calendar.MONTH, -1);

Then you can call getter on the Calendar to acquire proper fields

int month = c.get(Calendar.MONTH) + 1; // beware of month indexing from zero
int year  = c.get(Calendar.YEAR);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement