[java] 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.

This question is related to java calendar java-time

The answer is


Here's the code snippet.I think it works.

      Calendar cal = Calendar.getInstance();
      SimpleDateFormat simpleMonth=new SimpleDateFormat("MMMM YYYY");
      cal.add(Calendar.MONTH, -1);
      System.out.println(simpleMonth.format(prevcal.getTime()));

you can use the Calendar class to do so:

SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
System.out.println(format.format(cal.getTime()));

This prints : 2012.09.10 11:01 for actual date 2012.10.10 11:01


You need to be aware that month is zero based so when you do the getMonth you will need to add 1. In the example below we have to add 1 to Januaray as 1 and not 0

    Calendar c = Calendar.getInstance();
    c.set(2011, 2, 1);
    c.add(Calendar.MONTH, -1);
    int month = c.get(Calendar.MONTH) + 1;
    assertEquals(1, month);

private static String getPreviousMonthDate(Date date){
    final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

    Calendar cal = Calendar.getInstance();  
    cal.setTime(date);  
    cal.set(Calendar.DAY_OF_MONTH, 1);  
    cal.add(Calendar.DATE, -1);

    Date preMonthDate = cal.getTime();  
    return format.format(preMonthDate);
}


private static String getPreToPreMonthDate(Date date){
    final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

    Calendar cal = Calendar.getInstance();  
    cal.setTime(date);  
    cal.add(Calendar.MONTH, -1);  
    cal.set(Calendar.DAY_OF_MONTH,1);  
    cal.add(Calendar.DATE, -1);  

    Date preToPreMonthDate = cal.getTime();  
    return format.format(preToPreMonthDate);
}

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

The simplest & least error prone approach is... Use Calendar's roll() method. Like this:

    c.roll(Calendar.MONTH, false);

the roll method takes a boolean, which basically means roll the month up(true) or down(false)?


Use Joda Time Library. It is very easy to handle date, time, calender and locale with it and it will be integrated to java in version 8.

DateTime#minusMonths method would help you get previous month.

DateTime month = new DateTime().minusMonths (1); 

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to calendar

Moment.js get day name from date HTML Input Type Date, Open Calendar by default Check if a given time lies between two times regardless of date Creating java date object from year,month,day How to set time to 24 hour format in Calendar How to get Month Name from Calendar? Get first date of current month in java Specify the date format in XMLGregorianCalendar Getting last day of the month in a given string date How to change TIMEZONE for a java.util.Calendar/Date

Examples related to java-time

Why is ZoneOffset.UTC != ZoneId.of("UTC")? java.time.format.DateTimeParseException: Text could not be parsed at index 21 How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds? Convert LocalDateTime to LocalDateTime in UTC LocalDate to java.util.Date and vice versa simplest conversion? JSON Java 8 LocalDateTime format in Spring Boot serialize/deserialize java 8 java.time with Jackson JSON mapper Calculate days between two Dates in Java 8 How to get UTC+0 date in Java 8? Format LocalDateTime with Timezone in Java8