📜  Java中的 TimeUnit convert() 方法及示例

📅  最后修改于: 2022-05-13 01:55:28.144000             🧑  作者: Mango

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