Java中的 TimeUnit toMillis() 方法及示例
TimeUnit 类的toMillis()方法用于获取 TimeUnit 对象表示的时间,以秒数表示,自 1970 年 1 月 1 日午夜 UTC 起。
句法:
public long toMillis(long duration)
参数:此方法接受一个强制参数duration ,它是以毫秒为单位的持续时间。
返回值:此方法将转换后的持续时间返回为秒。
下面的程序说明了 TimeUnit toMillis() 方法的实现:
方案一:
// Java program to demonstrate
// toMillis() method of TimeUnit Class
import java.util.concurrent.*;
import java.util.Date;
class GFG {
public static void main(String args[])
{
// Get current time in seconds
long timeInSec = (new Date().getTime()) / 1000;
// Create a TimeUnit object
TimeUnit time = TimeUnit.SECONDS;
// Convert seconds to milliSeconds
// using toMillis() method
System.out.println("Time " + timeInSec
+ " Seconds in MilliSeconds = "
+ time.toMillis(timeInSec));
}
}
输出:
Time 1539585757 Seconds in MilliSeconds = 1539585757000
方案二:
// Java program to demonstrate
// toMillis() 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 timeInSec = (Calendar
.getInstance()
.getTimeInMillis())
/ 1000;
// Create a TimeUnit object
TimeUnit time = TimeUnit.SECONDS;
// Convert seconds to milliSeconds
// using toMillis() method
System.out.println("Time " + timeInSec
+ " Seconds in MilliSeconds = "
+ time.toMillis(timeInSec));
}
}
输出:
Time 1539585759 Seconds in MilliSeconds = 1539585759000