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
.
Use the getActualMaximum() method to get the last day of the month. int res = cal. getActualMaximum(Calendar. DATE);
Use LocalDate 's plusDays() and minusDays() method to get the next day and previous day, by adding and subtracting 1 from today.
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.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With