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


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


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

用法:

public long toSeconds(long duration)

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


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

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

示例1:

// Java program to demonstrate 
// toSeconds() 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 Seconds 
        // using toSeconds() method 
        System.out.println("Time " + timeInMilliSec 
                           + " milliSeconds in Seconds = "
                           + time.toSeconds(timeInMilliSec)); 
    } 
}
輸出:
Time 1539585656193 milliSeconds in Seconds = 1539585656

示例2:

// Java program to demonstrate 
// toSeconds() 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 Seconds 
        // using toSeconds() method 
        System.out.println("Time " + timeInMilliSec 
                           + " milliSeconds in Seconds = "
                           + time.toSeconds(timeInMilliSec)); 
    } 
}
輸出:
Time 1539585659342 milliSeconds in Seconds = 1539585659


相關用法


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