Java 獲取 Unix時間戳


unix時間戳是從1970年1月1日(UTC/GMT的午夜)開始所經過的秒數,不考慮閏秒。

在大多數的UNIX系統中UNIX時間戳存儲為32位,這樣會引發2038年問題。

但是,因為需求是需要int類型的UNIX時間戳。 開始的時候我是這樣設計的。

/**
	 * 獲取當前事件Unxi 時間戳
	 * @return
	 */
	public static int getUnixTimeStamp(){
		long rest=System.currentTimeMillis()/1000L;
		return (int)rest;
	}

 從新封裝了一些方法。如下穩定性就好很多了。

 1 package com.xuanyuan.utils;
 2 
 3 public class TimeUtils {
 4     
 5       /**
 6      * Constant that contains the amount of milliseconds in a second
 7      */
 8     static final long ONE_SECOND = 1000L;
 9 
10     /**
11      * Converts milliseconds to seconds
12      * @param timeInMillis
13      * @return The equivalent time in seconds
14      */
15     public static int toSecs(long timeInMillis) {
16         // Rounding the result to the ceiling, otherwise a
17         // System.currentTimeInMillis that happens right before a new Element
18         // instantiation will be seen as 'later' than the actual creation time
19         return (int)Math.ceil((double)timeInMillis / ONE_SECOND);
20     }
21 
22     /**
23      * Converts seconds to milliseconds, with a precision of 1 second
24      * @param timeInSecs the time in seconds
25      * @return The equivalent time in milliseconds
26      */
27     public static long toMillis(int timeInSecs) {
28         return timeInSecs * ONE_SECOND;
29     }
30 
31     /**
32      * Converts a long seconds value to an int seconds value and takes into account overflow
33      * from the downcast by switching to Integer.MAX_VALUE.
34      * @param seconds Long value
35      * @return Same int value unless long > Integer.MAX_VALUE in which case MAX_VALUE is returned
36      */
37     public static int convertTimeToInt(long seconds) {
38         if (seconds > Integer.MAX_VALUE) {
39             return Integer.MAX_VALUE;
40         } else {
41             return (int) seconds;
42         }
43     }
44 
45 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM