Date.getTime()返回自1970年1月1日以来的毫秒数。Unixtime是自1970年1月1日以来的秒数。我有:Date now = new Date(); Long longTime = new Long(now.getTime()/1000);return longTime.intValue();有没有更好的方法来在Java中获取unixtime?更新根据John M的建议,我最终得到:return (int) (System.currentTimeMillis() / 1000L);
3 回答

不负相思意
TA贡献1777条经验 获得超10个赞
避免使用System.currentTimeMillis()创建Date对象。除以1000将使您进入Unix时代。
如注释中所述,对于unixTime变量的类型,通常希望使用基元长(小写l长)而不是盒装对象长(大写L Long)。
long unixTime = System.currentTimeMillis() / 1000L;

撒科打诨
TA贡献1934条经验 获得超2个赞
Java 8添加了用于处理日期和时间的新API。使用Java 8,您可以使用
import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();
Instant.now()返回表示当前系统时间的Instant。有了,getEpochSecond()您将获得的纪元秒(unix时间)Instant。
添加回答
举报
0/150
提交
取消