11

Possible Duplicate:
Anyone know a simple way using java calendar to subtract X days to a date?

I need to minus 365 days in a given date (givenDate)-

Calendar calendar = Calendar.getInstance();
calendar.setTime(givenDate);
calendar.add(Calendar.DATE, -365);  

Am I right?

Community
  • 1
  • 1
Milli
  • 111
  • 1
  • 1
  • 3

5 Answers5

13

Calendar.DAY_OF_YEAR is the proper way to subtract days

You can also subtract a year (taking in to account leap years) by using

Calendar calendar = Calendar.getInstance();
calendar.setTime(givenDate);
calendar.add(Calendar.YEAR, -1);
KevMo
  • 5,590
  • 13
  • 57
  • 70
  • 2
    Actually calendar.add(Calendar.DAY_OF_YEAR, n) and calendar.add(Calendar.DATE, n) are identical. See http://stackoverflow.com/questions/2506082/add-more-than-30-days-with-calendars-add-method-in-java/2506096#2506096 – Juha Syrjälä Apr 12 '10 at 16:41
4

That is the correct way to subtract days.

Note that 365 days does not always equal one year because of leap days. calendar.add(Calendar.YEAR, -1) would subtract one year correctly.

You also may want to use Joda Time-library instead of java.util.Date and java.util.Calendar. Joda Time is a much nicer API for handling times and dates.

Casey
  • 12,070
  • 18
  • 71
  • 107
Juha Syrjälä
  • 33,425
  • 31
  • 131
  • 183
1

I don't think it'll make a different, but I would use Calendar.DAY_OF_YEAR as the field.

Ben S
  • 68,394
  • 30
  • 171
  • 212
0

If you are trying to strictly subtract 365 days, then yeah, that'd do it. However, if you are trying years backward, that might not work due to leap years.

luis.espinal
  • 10,331
  • 6
  • 39
  • 55
0

Check out Veyder-time. It is a simple and powerful alternativ to java.util.Calendar and has simple methods for adding and subtracting both days and years, among many other things.

lonerook
  • 99
  • 3