Duration

The Duration class is designed to represent a time-based duration, typically measured in seconds and nanoseconds. It offers a range of static methods for creating durations based on days, hours, minutes, seconds, milliseconds, and nanoseconds. Additionally, it provides conversion methods to express the duration in various units, as well as the ability to calculate the duration between two temporal objects. This class is ideal for measuring time spans, tracking elapsed time, and performing time-based calculations in applications.

Static Methods

ofDays(days: Long)

  • Obtains a Duration representing a number of standard 24-hour days.

  • Example Usage:

    var daysDuration = Duration.ofDays(5);

ofHours(hours: Long)

  • Obtains a Duration representing a number of standard hours.

  • Example Usage:

    var hoursDuration = Duration.ofHours(12);

ofMinutes(minutes: Long)

  • Obtains a Duration representing a number of standard minutes.

  • Example Usage:

    var minutesDuration = Duration.ofMinutes(30);

ofSeconds(seconds: Long)

  • Obtains a Duration representing a number of seconds.

  • Example Usage:

    var secondsDuration = Duration.ofSeconds(120);

ofMillis(millis: Long)

  • Obtains a Duration representing a number of milliseconds.

  • Example Usage:

ofNanos(nanos: Long)

  • Obtains a Duration representing a number of nanoseconds.

  • Example Usage:

parse(text: String)

  • Obtains a Duration from a text string such as PnDTnHnMn.nS.

  • Parses a textual representation of a duration, including the string produced by toString().

  • Example Usage:

Conversion Methods

toString()

  • A string representation of this duration using ISO-8601 seconds based representation, such as PT8H6M12.345S.

  • Example Usage:

toDays()

  • Gets the number of days in this duration.

  • Example Usage:

toHours()

  • Gets the number of hours in this duration.

  • Example Usage:

toMinutes()

  • Gets the number of minutes in this duration.

  • Example Usage:

toSeconds()

  • Gets the number of seconds in this duration.

  • Example Usage:

toMillis()

  • Converts this duration to the total length in milliseconds.

  • Example Usage:

toNanos()

  • Converts this duration to the total length in nanoseconds expressed as a long.

  • Example Usage:

between(startInclusive: any, endExclusive: any)

  • Obtains a Duration representing the duration between two temporal objects.

  • Example Usage:

Examples

Example: Days Ago

Description: This script calculates the number of days between a specified ‘order_date’ and the current date.

Use Case: Useful for tracking the time elapsed since an order was placed.

This example demonstrates how the Duration class can be used for tracking the age of data or calculating time-based metrics in various applications.

Last updated

Was this helpful?