一、System.currentTimeMillis()
public static long currentTimeMillis()
Java中最常用的獲取時間戳的方法是System.currentTimeMillis(),該方法返回當前時間距離1970年1月1日0時0分0秒的毫秒數。由於1秒等於1000毫秒,因此可以通過除以1000來得到秒級時間戳。
long timestamp = System.currentTimeMillis() / 1000L; System.out.println("當前秒級時間戳:" + timestamp);
以上代碼即可獲取當前的秒級時間戳。
System.currentTimeMillis()方法的優點是性能較高,最終結果只需進行一次除法運算即可得到秒級時間戳。但缺點也很明顯,它是依靠系統的時鐘來計時的,如果系統時鐘被修改,則獲取到的時間戳也會相應地改變。
二、Instant.now().getEpochSecond()
public static Instant now() public long getEpochSecond()
Java 8引入了新的時間API,其中Instant類用於表示一個瞬間,可以通過Instant.now()獲取當前的瞬間,然後通過getEpochSecond()方法獲取秒級時間戳。
long timestamp = Instant.now().getEpochSecond(); System.out.println("當前秒級時間戳:" + timestamp);
使用Instant.now().getEpochSecond()方法獲取秒級時間戳的優點是精確度高,不會受到系統時鐘的影響,缺點是相比於System.currentTimeMillis()方法稍微慢一些。
三、new Date().getTime()
public Date() public long getTime()
Date類可以用於表示一個日期和時間,可以通過new Date()獲取當前的日期和時間,然後通過getTime()方法獲取距離1970年1月1日0時0分0秒的毫秒數,最後通過除以1000來得到秒級時間戳。
long timestamp = new Date().getTime() / 1000L; System.out.println("當前秒級時間戳:" + timestamp);
使用new Date().getTime()方法獲取秒級時間戳的優點是簡便易用,缺點是Date類已經被Java官方標記為Deprecated,因此不推薦使用。
四、Clock.systemUTC().instant().getEpochSecond()
public static Clock systemUTC() public Instant instant() public long getEpochSecond()
Clock類可以用於提供一個時間源,其中systemUTC()方法返回格林威治標準時間的Clock,instant()方法返回當前時刻的Instant,然後通過getEpochSecond()方法獲取秒級時間戳。
long timestamp = Clock.systemUTC().instant().getEpochSecond(); System.out.println("當前秒級時間戳:" + timestamp);
使用Clock.systemUTC().instant().getEpochSecond()方法獲取秒級時間戳的優點是能夠提供可靠的時間源,缺點是代碼稍微有些繁瑣。
五、ThreadLocalRandom.current().nextInt()
public static ThreadLocalRandom current() public int nextInt()
ThreadLocalRandom類是Java 7引入的一個新類,用於生成隨機數,可以通過ThreadLocalRandom.current()獲取當前線程的ThreadLocalRandom對象,然後通過nextInt()方法生成一個隨機整數,然後將該隨機整數作為秒級時間戳。
int random = ThreadLocalRandom.current().nextInt(); long timestamp = random < 0 ? -random : random; System.out.println("當前秒級時間戳:" + timestamp);
使用ThreadLocalRandom.current().nextInt()方法生成秒級時間戳的優點是可以隨機產生一個大整數,缺點是可能會產生負數,需要進行相應的處理。
原創文章,作者:FMIOK,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/371084.html