Search code examples
javacalendarsubtraction

How to subtract X days from a date using Java calendar?


Anyone know a simple way using Java calendar to subtract X days from a date?

I have not been able to find any function which allows me to directly subtract X days from a date in Java. Can someone point me to the right direction?


Solution

  • Taken from the docs here:

    Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:

    Calendar calendar = Calendar.getInstance(); // this would default to now
    calendar.add(Calendar.DAY_OF_MONTH, -5).