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


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


TimeUnit類的convert()方法用於將給定單位的給定持續時間轉換為該單位。由於轉換涉及從較大的單位到較小的單位,或者從較小的單位到較大的單位,因此使用此方法可能會導致精度下降和溢出。

用法:

public long convert(long sourceDuration, 
                        TimeUnit sourceUnit)

參數:此方法接受兩個強製性參數:


  • sourceDuration–這是給定sourceUnit中的持續時間
  • sourceUnit–這是sourceDuration參數的單位

返回值:此方法以該單位返回轉換後的持續時間;如果轉換將負溢出,則返回Long.MIN_VALUE;如果正溢出,則返回Long.MAX_VALUE。

以下示例程序旨在說明TimeUnit convert()方法的實現:

示例1:將分鍾轉換為毫秒

// Java program to demonstrate 
// convert() method of TimeUnit Class 
  
import java.util.concurrent.*; 
import java.util.Date; 
  
class GFG { 
    public static void main(String args[]) 
    { 
        // Get time to be converted in Minutes 
        long timeInMinutes = 55L; 
  
        // Create a TimeUnit object 
        TimeUnit time = TimeUnit.MILLISECONDS; 
  
        // Convert Minutes to milliseconds 
        // using convert() method 
        System.out.println("Time " + timeInMinutes 
                           + " minutes in milliSeconds = "
                           + time.convert(timeInMinutes, 
                                          TimeUnit.MINUTES)); 
    } 
}
輸出:
Time 55 minutes in milliSeconds = 3300000

示例2:將秒轉換為分鍾

// Java program to demonstrate 
// convert() method of TimeUnit Class 
  
import java.util.concurrent.*; 
import java.util.Date; 
  
class GFG { 
    public static void main(String args[]) 
    { 
        // Get time to be converted in Seconds 
        long timeInSec = 300L; 
  
        // Create a TimeUnit object 
        TimeUnit time = TimeUnit.MINUTES; 
  
        // Convert Seconds to Minutes 
        // using convert() method 
        System.out.println("Time " + timeInSec 
                           + " seconds in minutes = "
                           + time.convert(timeInSec, 
                                          TimeUnit.SECONDS)); 
    } 
}
輸出:
Time 300 seconds in minutes = 5


相關用法


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