TimeUnit convert() method in Java with Examples
The convert() method of TimeUnit Class is used to convert the given time duration in the given unit to this unit. Since conversion involves from larger to smaller or smaller to larger units, loss of precision and overflow can occur while using this method.
public long convert(long sourceDuration, TimeUnit sourceUnit)
Parameters: This method accepts two mandatory parameters:
- sourceDuration– which is the time duration in the given sourceUnit
- sourceUnit– which is the unit of the sourceDuration argument
Return Value: This method returns the converted duration in this unit, or Long.MIN_VALUE if conversion would negatively overflow, or Long.MAX_VALUE if it would positively overflow.
Below program illustrate the implementation of TimeUnit convert() method:
Program 1: To convert Minutes to MilliSeconds
Time 55 minutes in milliSeconds = 3300000
Program 2: To convert Seconds to Minutes
Time 300 seconds in minutes = 5
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.