Compute the Difference between Two Dates

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Compute the Difference between Two Dates

This Java program shows how to compute the difference between two Dates.

[edit] Java Source Code

  • Package: example.calendardate
  • File: DateCalAdd.java
package example.calendardate;
 
import java.text.SimpleDateFormat;
import java.util.Calendar;
 
/**
 * 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.YEAR, -2);
	System.out.println("Two years ago was " + formatter.format(now.getTime()));
    }
}

[edit] What Result You Can Get

Run the program, you will get:


It is now Fri 2008/08/08 at 10:46:36 PM PDT
Two years ago was Tue 2006/08/08 at 10:46:36 PM PDT

[edit] Required External Libraries and/or Files for this Java Example

Need nothing.


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools