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 }

 

转载于:https://www.cnblogs.com/lynn-lkp/p/6224085.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值