JAVA比较2个Timestamp类型的时间大小-由此引发的思考

  今天忽然要对2个Timestamp变量的类型进行比较。没怎么用过,百度发现居然很多都是转换类型的。后面发现Timestamp自己都有方法进行比较。但是百度一堆都是那些要转换类型的。我就想简单的知道2个Timestamp的时间哪个早哪个晚嘛。

  经过自己的百度的验证,终于找到我想要的比较时间的最简便的方法。看代码吧。

public class MyTest {

    public static void main(String[] args) throws Exception {

        Timestamp a = Timestamp.valueOf("2018-05-18 09:32:32");
        Timestamp b = Timestamp.valueOf("2018-05-11 09:32:32");
        if (b.before(a)) {
            System.out.println("b时间比a时间早");
        }
        //Date转换Timestamp
        Timestamp timestamp = new Timestamp((new Date()).getTime());
        //Timestamp转换Date
        Timestamp timestamp1 = new Timestamp(System.currentTimeMillis());
        Date date = new Date(timestamp1.getTime());
    }
}

代码后面还附送Date和Timestamp互换的方法。原来Timestamp附送了比较2个时间的方法了。那就是before和after。而这2个方法的参数类型可以是Timestamp,也可以是Date。

  我们看它里面的是怎么实现的就会发现里面封装了一个compareTo()方法。

public boolean before(Timestamp ts) {
        return compareTo(ts) < 0;
    }

public int compareTo(Timestamp ts) {
        long thisTime = this.getTime();
        long anotherTime = ts.getTime();
        int i = (thisTime<anotherTime ? -1 :(thisTime==anotherTime?0 :1));
        if (i == 0) {
            if (nanos > ts.nanos) {
                    return 1;
            } else if (nanos < ts.nanos) {
                return -1;
            }
        }
        return i;
    }

这个compareTo的参数也可以是Date类型的。但是我发现它也是把Date类型转换成了Timestamp类型再调用上面的这个compareTo的方法。

public int compareTo(java.util.Date o) {
       if(o instanceof Timestamp) {
            // When Timestamp instance compare it with a Timestamp
            // Hence it is basically calling this.compareTo((Timestamp))o);
            // Note typecasting is safe because o is instance of Timestamp
           return compareTo((Timestamp)o);
      } else {
            // When Date doing a o.compareTo(this)
            // will give wrong results.
          Timestamp ts = new Timestamp(o.getTime());
          return this.compareTo(ts);
      }
    }

  那好,我们再看会compareTo()这个方法把。

  

long thisTime = this.getTime();

这一句就说明了是拿时间戳来比较的。

int i = (thisTime<anotherTime ? -1 :(thisTime==anotherTime?0 :1));

比较绕的就是这一句吧,这里使用了if-else的简洁写法。这样在一些繁琐的逻辑处理中还是挺好的,可以省却定义一些不必要的变量。代码也简洁多了,易读性提高了不少。如果你看多了这种写法,自然就会喜欢上了。

  起初,我也只是想查一下Timestamp的比较方法,没想到引出了这些思考。总结一下,java开发还是要熟悉这个自带类的API,如果不熟悉,平时在使用的时候就可以在定义完变量后加.来查看有哪些自己还不熟悉的但是也有用的方法。有时候比百度资料来的更直接。真的是不积跬步无以至千里啊。

结束分享一句歌词。


  过眼的不只云烟 

  有梦就有蓝天 相信就能看见

                                                                                                                                                 -梦想天空分外蓝


猜你喜欢

转载自blog.csdn.net/u010102390/article/details/80359847
今日推荐