Java TimeUnit toNanos()方法及示例
TimeUnit类 的 toNanos() 方法用于获取TimeUnit对象所代表的时间,作为1970年1月1日UTC午夜后的纳秒数。
语法:
public long toNanos(long duration)
参数: 该方法接受一个强制性参数 duration ,即以毫秒为单位的持续时间。
返回值: 该方法返回 转换后的持续时间 为纳秒。
以下程序说明了TimeUnit toNanos()方法的实现:
程序1:
// Java program to demonstrate
// toNanos() method of TimeUnit Class
import java.util.concurrent.*;
import java.util.Date;
class GFG {
public static void main(String args[])
{
// Get current time in milliseconds
long timeInMilliSec = new Date().getTime();
// Create a TimeUnit object
TimeUnit time = TimeUnit.MILLISECONDS;
// Convert milliseconds to NanoSeconds
// using toNanos() method
System.out.println("Time " + timeInMilliSec
+ " milliSeconds in NanoSeconds = "
+ time.toNanos(timeInMilliSec));
}
}
输出
Time 1539585501608 milliSeconds in NanoSeconds = 1539585501608000000
程序2:
// Java program to demonstrate
// toNanos() method of TimeUnit Class
import java.util.concurrent.*;
import java.util.Calendar;
class GFG {
public static void main(String args[])
{
// Get current time in milliseconds
long timeInMilliSec = Calendar
.getInstance()
.getTimeInMillis();
// Create a TimeUnit object
TimeUnit time = TimeUnit.MILLISECONDS;
// Convert milliseconds to NanoSeconds
// using toNanos() method
System.out.println("Time " + timeInMilliSec
+ " milliSeconds in NanoSeconds = "
+ time.toNanos(timeInMilliSec));
}
}
输出
Time 1539585503771 milliSeconds in NanoSeconds = 1539585503771000000