Calculate the Difference between Two Dates

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Calculate the Difference between Two Dates

This Java program shows how to calculate the difference between two dates.

[edit] Java Source Code

  • Package: example.calendardate
  • File: DateDiff.java
package example.calendardate;
 
import java.util.Date;
import java.util.GregorianCalendar;
 
/**
 * DateDiff -- compute the difference between two dates.
 */
public class DateDiff {
    public static void main(String[] av) {
	/** The date at the end of the last century */
	Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();
 
	/** Today's date */
	Date today = new Date();
 
	// Get msec from each, and subtract.
	long diff = today.getTime() - d1.getTime();
 
	System.out.println("The 21st century (up to " + today + ") is " + (diff / (1000 * 60 * 60 * 24)) + " days old.");
    }
}

[edit] What Result You Can Get

Run the program, you will get:


The 21st century (up to Fri Aug 08 22:58:44 PDT 2008) is 2776 days old.

[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