开发者

Why does my java time comparison fail?

开发者 https://www.devze.com 2023-03-02 18:16 出处:网络
I have the following method to convert String to date with millisecond granularity public Date convertTime(String 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");开发者_JS百科
    System.out.println(d1.after(d2));

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号