當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java TimeUnit toMillis()用法及代碼示例


自1970年1月1日午夜UTC以來,使用TimeUnit類的toMillis()方法獲取TimeUnit對象表示的時間(以秒為單位)。

用法:

public long toMillis(long duration)

參數:此方法接受強製參數持續時間,該持續時間以毫秒為單位。


返回值:此方法將轉換後的持續時間返回為秒。

下麵的程序演示了TimeUnit toMillis()方法的實現:

示例1:

// 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

示例2:

// 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


相關用法


注:本文由純淨天空篩選整理自RishabhPrabhu大神的英文原創作品 TimeUnit toMillis() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。