Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get previous year from the result of current year in java?

Tags:

java

public class CalendarCal {

    public static void main(String[] args) {
        Date date = new Date();
        SimpleDateFormat simpleDateformat = new SimpleDateFormat("yy");
        String m = simpleDateformat.format(date);
        System.out.println("Year:" + m);
        int year = Calendar.getInstance().get(Calendar.YEAR) % 100;
        System.err.println(year);
    }
}

I am able to retrieve the current year from this. How can I get the last (previous) year with help of utility? I don't want to do a calculation like currentyear - 1 or like that.

like image 446
jcrshankar Avatar asked Feb 23 '12 10:02

jcrshankar


People also ask

How can I get previous date in Java?

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

How do I get the current year in Java?

The now() method of this class obtains the current date from the system clock. The getYear() method returns an integer representing the year filed in the current LocalDate object. The getMonth() method returns an object of the java. timeMonth class representing the month in the LocalDate object.

How do you check if a date is after another date in Java?

To compare dates if a date is after another date, use the Calendar. after() method.


1 Answers

Just use Calendar.add method to "add" -1 to the year and wrap it in your own utility method:

private static int getPreviousYear() {
    Calendar prevYear = Calendar.getInstance();
    prevYear.add(Calendar.YEAR, -1);
    return prevYear.get(Calendar.YEAR);
}

Example:

public static void main(String[] args) {
    System.out.println(getPreviousYear());
}

Prints on my system:

2011
like image 127
dacwe Avatar answered Sep 19 '22 20:09

dacwe