Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata