Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting days in a Calendar object [duplicate]

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?

like image 828
Milli Avatar asked Apr 12 '10 16:04

Milli


3 Answers

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);
like image 141
KevMo Avatar answered Nov 01 '22 23:11

KevMo


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.

like image 30
Juha Syrjälä Avatar answered Nov 01 '22 23:11

Juha Syrjälä


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

like image 42
Ben S Avatar answered Nov 02 '22 00:11

Ben S