O'Reilly logo

Java Cookbook by Ian F. Darwin

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

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

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