如何将System.nanoTime的结果转换为Java的日期? [英] How can I convert the result of System.nanoTime to a date in Java?

查看:1836
本文介绍了如何将System.nanoTime的结果转换为Java的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换 System.nanoTime() 到日期。

I want to convert the result of System.nanoTime() to a date.

public void tempBan(Player p, Player banner, int timeInSeconds){
    Long timeInNano = (long) (timeInSeconds * 10^9);
    int newTime = (int) (System.nanoTime() + timeInNano);
    // here I want to convert newTime to a date 
}

我已将秒数乘以10 ^ 9,将秒数转换为纳秒秒。现在我需要将当前系统时间加上我转换成纳秒的参数转换成一个日期。

I have converted the seconds into nanoseconds by multiplying by 10^9. Now I need to convert the current system time plus the parameter which I converted into nanoseconds into a date.

推荐答案

不幸的是,code> System.nanoTime()不是你想要的。

Unfortunately, System.nanoTime() is not what you want for this.

引用Javadoc为 System.nanoTime()

To quote the Javadoc for System.nanoTime():


此方法只能用于测量已用时间,与任何其他系统或挂钟时间的概念。返回的值表示纳秒,因为一些固定但任意的起始时间(可能在将来,所以值可能是负数)。在Java虚拟机的实例中,该方法的所有调用都使用相同的来源;其他虚拟机实例可能会使用不同的来源。

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.

您可能需要 System.currentTimeMillis(),在这种情况下,您可以使用新的Date(System.currentTimeMillis()+ milliseconds)来获取将来该毫秒数的日期。

You probably want System.currentTimeMillis(), in which case you can use new Date(System.currentTimeMillis() + milliseconds) to get the date for that number of milliseconds in the future.

虽然可以减去 System.nanoTime(),缩放该值,然后添加 System.currentTimeMillis()具有类似的结果...因为你添加 System.nanoTime(),因此拥有原始秒数,您可以直接使用 System.currentTimeMillis()

While you could then subtract System.nanoTime(), scale the value, and add System.currentTimeMillis() to have a similar result... since you're adding System.nanoTime() anyway and therefore have the original number of seconds, you could just use System.currentTimeMillis() directly.

这篇关于如何将System.nanoTime的结果转换为Java的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆