Skip to content

Time API

Tom Tzook edited this page Jul 19, 2019 · 2 revisions

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.

API

The API exports two important elements: Time and Clock.

Time

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 new Time 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();

Invalid Time

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.

Clock

The Clock interface represents a clock, which is capable of providing the current time, as Time, using the currentTime method.

Implementations

There are several base implementations:

  • JavaMillisClock: uses the System.currentTimeMillis.
  • JavaNanosClock: uses the System.nanoTime call.