Getting “unixtime” in Java

匿名 (未验证) 提交于 2019-12-03 02:06:01

问题:

Date.getTime() returns milliseconds since Jan 1, 1970. Unixtime is seconds since Jan 1, 1970. I don't usually code in java, but I'm working on some bug fixes. I have:

Date now = new Date();       Long longTime = new Long(now.getTime()/1000); return longTime.intValue(); 

Is there a better way to get unixtime in java?

UPDATE

Based on John M's suggestion, I ended up with:

return (int) (System.currentTimeMillis() / 1000L); 

回答1:

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L; 


回答2:

Java 8 added a new API for working with dates and times. With Java 8 you can use

long unixTimestamp = Instant.now().getEpochSecond(); 

Instant.now() returns an Instant that represents the current system time. With getEpochSecond() you get the epoch seconds (unix time) from the Instant.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!