
Java獲取當(dāng)前時(shí)間的幾種方法
開發(fā)過程中,可能會(huì)遇到精確的時(shí)間差值計(jì)算,可以使用System.nanoTime();方法獲取當(dāng)前系統(tǒng)的納秒值。不過該方法只能用于測(cè)量經(jīng)過時(shí)間,與系統(tǒng)時(shí)間的任何其他概念無(wú)關(guān)。用途:計(jì)算時(shí)間差,當(dāng)隨機(jī)數(shù)來(lái)使用(不建議)。
獲取當(dāng)前時(shí)間的毫秒值:System.currentTimeMillis();返回long型。
通過java.util.Date實(shí)例中的getTime()方法獲取當(dāng)前時(shí)間的毫秒值(從1970年1月1日算起),此方法在開發(fā)中經(jīng)常被使用。如果只是為了獲取當(dāng)前時(shí)間的毫秒值,其實(shí)是沒必要這么做的,直接使用System.currentTimeMillis()即可獲取。下圖Java源碼中,當(dāng)實(shí)例化一個(gè)Date對(duì)象的時(shí)候,其實(shí)使用的就是System.currentTimeMillis(),接著使用getTime()再讓JVM去計(jì)算一遍獲取當(dāng)前毫秒值實(shí)在是多次一舉,耗費(fèi)了性能。
Instant:JAVA8新特性,獲取當(dāng)前瞬間的實(shí)例。如果想要獲取更精確的納秒級(jí)時(shí)間值,可以使用Instant對(duì)象。Instant中不提供公共的構(gòu)造方法,因此只能使用靜態(tài)方法獲取Instant實(shí)例。簡(jiǎn)單介紹一下Instant對(duì)象中的常用方法。
- Instant.now();獲取當(dāng)前時(shí)間的瞬間實(shí)例,靜態(tài)方法,返回Instant類型
- getEpochSecond();得到瞬間實(shí)例的秒值
- toEpochMilli();得到瞬間實(shí)例的毫秒值
- getNano();得到瞬間實(shí)例的納秒值
- isAfter(Instant instant);比較這個(gè)瞬間是否在指定的時(shí)刻之后
- isBefore(Instant instant);比較這個(gè)瞬間是否在指定的時(shí)刻之前
- equals(Instant instant);檢查這個(gè)瞬間是否等于指定的時(shí)刻
代碼
????//該方法只能用于測(cè)量經(jīng)過時(shí)間,與系統(tǒng)時(shí)間的任何其他概念無(wú)關(guān)。用途:計(jì)算時(shí)間差,當(dāng)隨機(jī)數(shù)來(lái)使用(不建議)
????System.out.println(System.nanoTime());//47307604336560 ????//獲取系統(tǒng)當(dāng)前時(shí)間的毫秒值,從1970 年 1 月 1 日起計(jì)算 ????System.out.println(System.currentTimeMillis());//1541509585320 ????//獲取系統(tǒng)當(dāng)前時(shí)間的毫秒值,不建議這么使用.建議使用上面的方法. ????System.out.println(new Date().getTime());//1541509585322 ????? ????//獲取當(dāng)前瞬間的實(shí)例,JAVA8新特性 ????Instant instant = Instant.now(); ????System.out.println(instant);//2018-11-06T13:06:25.353Z ????//得到當(dāng)前瞬間的秒數(shù) ????System.out.println(instant.getEpochSecond());//1541509585 ????//得到當(dāng)前瞬間的毫秒數(shù) ????System.out.println(instant.toEpochMilli());//1541509585353 ????//得到當(dāng)前瞬間的納秒數(shù) ????System.out.println(instant.getNano());//353000000 ????? ????Instant instantA= Instant.now(); ????//比較兩個(gè)instant的前后關(guān)系,返回boolean類型 ????System.out.println(instant.isAfter(instantA));//false ????System.out.println(instant.isBefore(instantA));//true ????//比較兩個(gè)instant是否相等 ????System.out.println(instant.equals(instantA));//false
[超站]友情鏈接:
四季很好,只要有你,文娛排行榜:https://www.yaopaiming.com/
關(guān)注數(shù)據(jù)與安全,洞悉企業(yè)級(jí)服務(wù)市場(chǎng):https://www.ijiandao.com/

隨時(shí)掌握互聯(lián)網(wǎng)精彩
- 1 這一天致青年 我們?nèi)绾钨s續(xù)與傳承 7903995
- 2 “第一天出去旅游的人已老實(shí)” 7809182
- 3 男子送老人過馬路 3次敬禮全網(wǎng)刷屏 7713223
- 4 中國(guó)假期吸引世界流量 7616680
- 5 張嘉益《人民日?qǐng)?bào)》撰文 7522029
- 6 90后美女副教授走紅 北航回應(yīng) 7428859
- 7 網(wǎng)警提醒:國(guó)慶歡樂游 安全別松懈 7330524
- 8 走失小狗在服務(wù)區(qū)苦等主人8小時(shí) 7233792
- 9 “課本上的傳奇”珍·古道爾逝世 7143036
- 10 多省發(fā)文補(bǔ)貼社保個(gè)人繳費(fèi)額的25% 7043109