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?
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.
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.
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
The last value is milliseconds .. 39 is greater than 4. 40 is greater than 39.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With