I want to pass around a time number and the TimeUnit
it is in.
long number = some number;
TimeUnit timeUnit = some arbitrary time unit
What can hold both the time and timeUnit in one Object
from the Java libraries?
TimeUnit is just enum holding some time unit types like Second, Milliseconds, ...
TimeUnit is NOT for holding time BUT you can convert a time in a unit to another unit using TimeUnit API.
I think you have to create your object to hold time and its unit.
If you use Java 8. You can work with some new Date API
http://download.java.net/jdk8/docs/api/java/time/package-summary.html
In Joda-Time there is an Interval, but you'll need to create a Java Bean (perhaps calling it Interval) if you want to use only JRE inclusive Object types.
There is no Java library object that encapsulates a number and an arbitrary
TimeUnit
. However, there is one in Java 8 that converts itself into whatever time unit is required:Duration stores the provided quantity and then provides comparison and conversion to all other time units. For example:
Of course, if doing addition and subtraction or other math operations, the precision is only as good as the precision of the current operation and the supplied
Duration
.And there are many more methods in Duration that are useful for converting and processing the stored quantity in various unit.
It is important to understand how the precision will affect calculations. This shows the general precision contract by example:
In a nutshell .. I cannot believe it took me this long to find
Duration
! :)