O'Reilly logo

Java™ Phrasebook by Timothy Fisher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding to or Subtracting from a Date or Calendar

// date arithmetic using Date objects
											Date date = new Date();
											long time = date.getTime();
											time += 5*24*60*60*1000;
											Date futureDate = new Date(time);
											// date arithmetic using Calendar objects
											Calendar nowCal = Calendar.getInstance();
											nowCal.add(Calendar.DATE, 5);

If you are using a Date object, the technique for adding or subtracting dates is to first convert the object to a long value using the getTime() method of the Date object. The getTime() method returns the time as measured in milliseconds since the epoch (January 1, 1970, 00:00:00 GMT). You then perform the arithmetic on the long values, and finally convert back to date objects. In the phrase shown, we are adding 5 days to the date object. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required