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. We convert the 5 days to milliseconds by multiplying by the number of hours in a day (24), the number of minutes in an hour (60), the number of seconds in a minute (60), and finally by 1,000 to convert from seconds to milliseconds.

You can perform date arithmetic directly on Calendar objects using the add() method. The add() method accepts two parameters, a field, and an amount, both int parameters. The quantity specified in the amount field is added to the field specified in the field parameter. The field could be any valid date field, such as day, week, month, year, etc. To subtract time, you would set the amount value to be a negative number. By setting the field parameter to the appropriate Calendar constant, you can directly add or subtract days, weeks, months, years, and so on. In the second part of our phrase, we show how to add 5 days to a Calendar object.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net