Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 906
ashishjmeshram Avatar asked Oct 10 '12 07:10

ashishjmeshram


People also ask

Is last day of month Java?

Use the getActualMaximum() method to get the last day of the month. int res = cal. getActualMaximum(Calendar. DATE);

How do I set the previous date in Java?

Use LocalDate 's plusDays() and minusDays() method to get the next day and previous day, by adding and subtracting 1 from today.

How do you calculate months in Java?

Once you have the LocalDate, you can use Months. monthsBetween() and Years. yearsBetween() method to calcualte the number of months and years between two dates in Java. LocalDate jamesBirthDay = new LocalDate(1955, 5, 19); LocalDate now = new LocalDate(2015, 7, 30); int monthsBetween = Months.


2 Answers

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); 
like image 146
Gaim Avatar answered Sep 20 '22 05:09

Gaim


java.time

Using java.time framework built into Java 8:

import java.time.LocalDate;  LocalDate now = LocalDate.now(); // 2015-11-24 LocalDate earlier = now.minusMonths(1); // 2015-10-24  earlier.getMonth(); // java.time.Month = OCTOBER earlier.getMonth.getValue(); // 10 earlier.getYear(); // 2015 
like image 36
Przemek Avatar answered Sep 23 '22 05:09

Przemek