Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my java time comparison fail?

Tags:

java

time

I have the following method to convert String to date with millisecond granularity

public Date convertTime(String time) {

    SimpleDateFormat parser = new SimpleDateFormat("HH:mm:ss.S");
    try {
        return parser.parse(time);
    }
    catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }


}

    Date d1 = lib.convertTime("10:30:53.39");
    Date d2 = lib.convertTime("10:30:53.40");
    System.out.println(d1.after(d2));

returns false as expected

However the following

    Date d1 = lib.convertTime("10:30:53.39");
    Date d2 = lib.convertTime("10:30:53.4");
    System.out.println(d1.after(d2));

Which I thought would have been the same returns true. What am I doing wrong?

like image 714
deltanovember Avatar asked May 05 '11 02:05

deltanovember


People also ask

How can I compare two dates in Java 11?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.

How do you compare years in Java?

The compareTo() method of Year class in Java is used to compare this Year object with another Year object. The comparison of Year object is based on the values of Year. Parameter: This method accepts a single parameter otherYear.


2 Answers

The confusion is due to the fact that the period is just a parsing token separator, not a numerical decimal separator. Substitute the symbol with, say, :, and the difference is clearer.

That is, in locales where . is the decimal separator, numerically 1.5 = 1.50 = 1.500.

However, when we parse the strings "1.5", "1.50", "1.500", using . as a token separator, we get (1, 5), (1, 50), (1, 500). The . has no special mathematical meaning here, and it could just as well be, say, a single whitespace.

This simple snippet also demonstrates the point:

    SimpleDateFormat parser = new SimpleDateFormat("Z s#S");

    System.out.println(parser.parse("GMT 1#002").getTime());  // 1002
    System.out.println(parser.parse("GMT 1#02").getTime());   // 1002
    System.out.println(parser.parse("GMT 1#2").getTime());    // 1002
    System.out.println(parser.parse("GMT 1#20").getTime());   // 1020
    System.out.println(parser.parse("GMT 1#200").getTime());  // 1200
like image 187
polygenelubricants Avatar answered Oct 16 '22 14:10

polygenelubricants


The last value is milliseconds .. 39 is greater than 4. 40 is greater than 39.

like image 35
Kal Avatar answered Oct 16 '22 15:10

Kal