Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java Date Compare
package introtocs;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class DateCompare {
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2009-12-31");
Date date2 = sdf.parse("2010-01-31");
// Check if date 1 is before date 2
if (date1.before(date2)) {
System.out.println("Its before");
}
// Check if date 1 is after date 2
if (date1.after(date2)) {
System.out.println("It's after.");
}
// Check if date 1 = date 2
if (date1.compareTo(date2) == 0) {
System.out.println("It's equal");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment