1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
/* Compare two Java Date objects using after method example. This example shows how to compare two java Date objects using after method of java Date Class. */ import java.util.Date; public class CompareDateUsingAfterExample{ public static void main(String[] args) { //create first date object Date d1 = new Date(); //make interval of 10 millisecond before creating second date object try{ Thread.sleep(10); }catch(Exception e){ } //create second date object Date d2 = new Date(); //use boolean after(Date anotherDate) method of Date Class to //check whether a date is after the specified date System.out.println("First Date : " + d1); System.out.println("Second Date : " + d2); System.out.println("Is second date after first ? : " + d2.after(d1)); } } /* TYPICAL Output Would be First Date : Sun Sep 09 19:43:12 EDT 2007 Second Date : Sun Sep 09 19:43:12 EDT 2007 Is second date after first ? : true */ |
It would be nice to show a 10ms time difference between two Date objects using Date.toString(), which the example implicitly calls. Unfortunately Date.toString() truncates the fractional seconds. Here is a short little method I cooked up that takes a Date object and returns the String object identical to Date.toString(), but with the seconds displayed with millisecond precision:
private String showDateWithMillis(Date date) {
String str = date.toString();
StringBuilder sb = new StringBuilder(str);
int millis = (int)(date.getTime()%1000);
str = Integer.toString(millis);
str = (str.length()<3 ? “0” : “”) + str; // 0 pad cases of 1 or 2 digits
str = (str.length()<3 ? “0” : “”) + str;
return sb.insert(19, “.” + str).toString();
}
Edit the two lines that do the console output:
System.out.println(“First Date : ” + showDateWithMillis(d1));
System.out.println(“Second Date : ” + showDateWithMillis(d2));
Console output will now look something like this:
First Date : Thu Sep 06 17:36:36.861 CDT 2012
Second Date : Thu Sep 06 17:36:36.871 CDT 2012
Is second date after first ? : true