当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。