您好,登錄后才能下訂單哦!
使用java獲取時(shí)間戳的方法有哪些?針對這個(gè)問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。
一、java獲取時(shí)間戳
首先我們先拿上面的例子說起吧。如何獲取今天零點(diǎn)以及明天零點(diǎn)的兩個(gè)時(shí)間戳。
public Long getToday(){ DateTime now = new DateTime(); return new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), 0, 0, 0, 0).getMillis(); } public Long getTomorrow(){ DateTime now = new DateTime(); return new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), 0, 0, 0, 0).plusDays(1).getMillis(); }
上面的方法中用到了DateTime中的plusDays(),同理,你如果需要獲取下 個(gè)星期(年,月,時(shí),分,秒,毫秒)前的時(shí)間戳,都有同樣的plusYears(int X),plusMonths(int X)等等與之對應(yīng),如果要獲取今天之前的就把傳入一個(gè)負(fù)整數(shù)參數(shù)即可。
然而很多時(shí)候我們需要某個(gè)特定時(shí)間的時(shí)間戳,比如這個(gè)月5號(hào)14點(diǎn)23分6秒138毫秒的時(shí)間戳(這個(gè)時(shí)間并沒有特殊的含義,隨便選的)。
public Long getTime(){ Long now = new Date().getTime(); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(now); calendar.set(Calendar.DAY_OF_MONTH, 5); calendar.set(Calendar.HOUR, 14); calendar.set(Calendar.MINUTE, 23); calendar.set(Calendar.SECOND, 6); calendar.set(Calendar.MILLISECOND, 138); return calendar.getTimeInMillis(); }
再比如我們可能需要知道這個(gè)星期二的10點(diǎn)10分10秒的時(shí)間戳。
public Long getTime(){ Long now = new Date().getTime(); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(now); calendar.set(Calendar.DAY_OF_WEEK, 2); calendar.set(Calendar.HOUR, 10); calendar.set(Calendar.MINUTE, 10); calendar.set(Calendar.SECOND, 10); return calendar.getTimeInMillis(); }
二、Java中兩種獲取精確到秒的時(shí)間戳的方法
Java中的時(shí)間戳的毫秒主要通過最后的三位來進(jìn)行計(jì)量的,下面給大家分享從網(wǎng)上整理的兩種不同的方式將最后三位去掉。
方法一:通過String.substring()方法將最后的三位去掉
/** * 獲取精確到秒的時(shí)間戳 * @return */ public static int getSecondTimestamp(Date date){ if (null == date) { return 0; } String timestamp = String.valueOf(date.getTime()); int length = timestamp.length(); if (length > 3) { return Integer.valueOf(timestamp.substring(0,length-3)); } else { return 0; } }
方法二:通過整除將最后的三位去掉
/** * 獲取精確到秒的時(shí)間戳 * @param date * @return */ public static int getSecondTimestampTwo(Date date){ if (null == date) { return 0; } String timestamp = String.valueOf(date.getTime()/1000); return Integer.valueOf(timestamp); }
關(guān)于使用java獲取時(shí)間戳的方法有哪些問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。