java timestamp是什么类型_JAVA比较2个Timestamp类型的时间大小-由此引发的思考
今天忽然要對(duì)2個(gè)Timestamp變量的類型進(jìn)行比較。沒(méi)怎么用過(guò),百度發(fā)現(xiàn)居然很多都是轉(zhuǎn)換類型的。后面發(fā)現(xiàn)Timestamp自己都有方法進(jìn)行比較。但是百度一堆都是那些要轉(zhuǎn)換類型的。我就想簡(jiǎn)單的知道2個(gè)Timestamp的時(shí)間哪個(gè)早哪個(gè)晚嘛。
經(jīng)過(guò)自己的百度的驗(yàn)證,終于找到我想要的比較時(shí)間的最簡(jiǎn)便的方法。看代碼吧。
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時(shí)間比a時(shí)間早");
}
//Date轉(zhuǎn)換Timestamp
Timestamp timestamp = new Timestamp((new Date()).getTime());
//Timestamp轉(zhuǎn)換Date
Timestamp timestamp1 = new Timestamp(System.currentTimeMillis());
Date date = new Date(timestamp1.getTime());
}
}
代碼后面還附送Date和Timestamp互換的方法。原來(lái)Timestamp附送了比較2個(gè)時(shí)間的方法了。那就是before和after。而這2個(gè)方法的參數(shù)類型可以是Timestamp,也可以是Date。
我們看它里面的是怎么實(shí)現(xiàn)的就會(huì)發(fā)現(xiàn)里面封裝了一個(gè)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 = (thisTimets.nanos) {
return 1;
} else if (nanos < ts.nanos) {
return -1;
}
}
return i;
}
這個(gè)compareTo的參數(shù)也可以是Date類型的。但是我發(fā)現(xiàn)它也是把Date類型轉(zhuǎn)換成了Timestamp類型再調(diào)用上面的這個(gè)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);
}
}
那好,我們?cè)倏磿?huì)compareTo()這個(gè)方法把。
long thisTime = this.getTime();
這一句就說(shuō)明了是拿時(shí)間戳來(lái)比較的。
int i = (thisTime
比較繞的就是這一句吧,這里使用了if-else的簡(jiǎn)潔寫法。這樣在一些繁瑣的邏輯處理中還是挺好的,可以省卻定義一些不必要的變量。代碼也簡(jiǎn)潔多了,易讀性提高了不少。如果你看多了這種寫法,自然就會(huì)喜歡上了。
起初,我也只是想查一下Timestamp的比較方法,沒(méi)想到引出了這些思考。總結(jié)一下,java開發(fā)還是要熟悉這個(gè)自帶類的API,如果不熟悉,平時(shí)在使用的時(shí)候就可以在定義完變量后加.來(lái)查看有哪些自己還不熟悉的但是也有用的方法。有時(shí)候比百度資料來(lái)的更直接。真的是不積跬步無(wú)以至千里啊。
結(jié)束分享一句歌詞。
過(guò)眼的不只云煙
有夢(mèng)就有藍(lán)天 相信就能看見(jiàn)
-夢(mèng)想天空分外藍(lán)
總結(jié)
以上是生活随笔為你收集整理的java timestamp是什么类型_JAVA比较2个Timestamp类型的时间大小-由此引发的思考的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 民间传说的故事20个合集
- 下一篇: java 统计数字个数_统计数字问题(J