Compare Dates Demo

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Compare Dates Demo

This Java program shows how to compare dates.

[edit] Java Source Code

  • Package: example.calendardate
  • File: CompareDates.java
package example.calendardate;
 
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class CompareDates {
    public static void main(String[] args) throws ParseException {
 
	DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
 
	// Get Date 1
	Date d1 = df.parse("2000-02-01");
 
	// Get Date 2
	Date d2 = df.parse("2001-03-02");
 
	String relation;
	if (d1.equals(d2))
	    relation = "the same date as";
	else if (d1.before(d2))
	    relation = "before";
	else
	    relation = "after";
	System.out.println(d1 + " is " + relation + ' ' + d2);
    }
}

[edit] What Result You Can Get

Run the program, you will get:


Tue Feb 01 00:00:00 PST 2000 is before Fri Mar 02 00:00:00 PST 2001

[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