Why is my java time comparison failing?

I have the following method for converting String to a 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 be the same, true. What am I doing wrong?

+6
source share
2 answers

The confusion is due to the fact that a period is just a parser separator, not a numeric decimal separator. Replace the character with, say : and the difference will be clearer.

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

However, when we analyze the lines "1.5" , "1.50" , "1.500" using . as a token separator, we get (1, 5) , (1, 50) , (1, 500) . . there is no special mathematical value, and this may be, say, the only gap.

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 
+6
source

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

+4
source

Source: https://habr.com/ru/post/887329/


All Articles