unix時間戳是從1970年1月1日(UTC/GMT的午夜)開始所通過的秒數,不考慮閏秒。java
在大多數的UNIX系統中UNIX時間戳存儲爲32位,這樣會引起2038年問題。app
可是,由於需求是須要int類型的UNIX時間戳。 開始的時候我是這樣設計的。less
/** * 獲取當前事件Unxi 時間戳 * @return */ public static int getUnixTimeStamp(){ long rest=System.currentTimeMillis()/1000L; return (int)rest; }
重新封裝了一些方法。以下穩定性就好不少了。ui
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 }