Java 获取 Unix时间戳

时间:2022-10-06 02:37:21

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 }