Adding to or Subtracting from a Date or Calendar
Problem
You need to add or subtract a fixed amount to or from a date.
Solution
As we’ve seen, Date
has a getTime( )
method that returns the number
of
seconds since the epoch as a long
. To add or
subtract, you just do arithmetic on this value. Here’s a code
example:
// DateAdd.java /** Today's date */ Date now = new Date( ); long t = now.getTime( ); t -= 700*24*60*60*1000; Date then = new Date(t); System.out.println("Seven hundred days ago was " + then);
Discussion
A cleaner variant is to use the Calendar
’s
add( )
method:
import java.text.*; import java.util.*; /** DateCalAdd -- compute the difference between two dates. */ public class DateCalAdd { public static void main(String[] av) { /** Today's date */ Calendar now = Calendar.getInstance( ); /* Do "DateFormat" using "simple" format. */ SimpleDateFormat formatter = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); System.out.println("It is now " + formatter.format(now.getTime( ))); now.add(Calendar.DAY_OF_YEAR, - (365 * 2)); System.out.println("Two years ago was " + formatter.format(now.getTime( ))); } }
Running this reports the current date and time, and the date and time two years ago:
> java DateCalAdd It is now Fri 2000.11.03 at 07:16:26 PM EST Two years ago was Wed 1998.11.04 at 07:16:26 PM EST
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.