Java Date Class

Compare two Java Date objects using after method example

Want to learn quickly?
Try one of the many quizzes. More than Java 400 questions with detailed answers.

Add Comment

  • 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

Sponsors

Facebook Fans