-
Notifications
You must be signed in to change notification settings - Fork 0
Time API
FlashLib introduces a new Time API, providing a more clean approach for handling time, without having to using primitive data types, or worrying about measurement units. Located under com.flash3388.flashlib.util.time
.
The API exports two important elements: Time
and Clock
.
The Time
class represents a time value, including size and measurement units. This is an immutable class, representing a fixed time.
There are several operations which can be done with this class:
- Math operations:
add
,sub
. Each producing a newTime
instance. - Comparison: it is possible to compare between times with:
-
largerThan
/after
-
lessThan
/before
largerThanOrEquals
lessThanOrEquals
equals
-
For example, comparing time passed:
final Time interval = ...
Time start = ...
Time current = ...
boolean intervalPassed = current.sub(start).largerThanOrEquals(interval);
When working with Time
, it is generally not necessary to access the measurement units, until it is required to pass it forward to another API. In such a case, it is best to use the toUnit
to ensure that the Time
is represented as the wanted unit, and only then to use value
to retrieve the value.
For example:
Time time = ....
long minutes = time.toUnit(TimeUnit.MINUTES).value();
Instead of using null
to represent an invalid time that was not set, similar to how time is set to a negative value when using primitives, The Time
API supports invalid time.
To define time as invalid, use Time time = Time.INVALID
.
To query whether time is valid or not, use time.isValid()
.
It is recommended to not use invalid to during operations, as it may lead to unexpected results.
The Clock
interface represents a clock, which is capable of providing the current time, as Time
, using the currentTime
method.
There are several base implementations:
-
JavaMillisClock
: uses theSystem.currentTimeMillis
. -
JavaNanosClock
: uses theSystem.nanoTime
call.