在 Java 中获取“unixtime”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/732034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting "unixtime" in Java
提问by Gary Richardson
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.getTime() 返回自 1970 年 1 月 1 日以来的毫秒数。Unixtime 是自 1970 年 1 月 1 日以来的秒数。我通常不使用 Java 编写代码,但我正在修复一些错误。我有:
Date now = new Date();
Long longTime = new Long(now.getTime()/1000);
return longTime.intValue();
Is there a better way to get unixtime in java?
有没有更好的方法在java中获得unixtime?
采纳答案by John M
Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.
避免使用System.currentTimeMillis()创建 Date 对象。除以 1000 使您进入 Unix 时代。
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.
正如评论中提到的,对于 unixTime 变量的类型,您通常需要原始 long(小写-l long)而不是装箱对象 long(大写-L Long)。
long unixTime = System.currentTimeMillis() / 1000L;
回答by micha
Java 8 added a new API for working with dates and times. With Java 8 you can use
Java 8 添加了一个用于处理日期和时间的新 API。使用 Java 8,您可以使用
import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();
Instant.now()
returns an Instantthat represents the current system time. With getEpochSecond()
you get the epoch seconds (unix time) from the Instant
.
Instant.now()
返回一个表示当前系统时间的Instant。随着getEpochSecond()
您从Instant
.