Module time
API
ballerina/time Ballerina library
Overview
This module provides APIs to generate and manipulate UTC and localized time, with nanosecond precision and support for complex cases such as leap seconds and daylight saving time.
Key Features
- UTC time generation and manipulation with nanosecond precision
- Monotonic time for measuring elapsed durations from an unspecified epoch
- Civil (localized) time with date, time, timezone, and daylight saving information
- Time zone lookup by zone ID or system default
- Conversions between UTC, Civil, and RFC 3339 string representations
UTC time
The time:Utc is the tuple representation of the UTC. The UTC represents the number of seconds from a specified epoch. Here, the epoch is the UNIX epoch of 1970-01-01T00:00:00Z.
Use the following API to get the current epoch time:
time:Utc utc = time:utcNow();
Monotonic time
The monotonic time represents the number of seconds from an unspecified epoch.
Use the following API to get the monotonic time from an unspecified topic:
decimal seconds = time:monotonicNow();
Civil time
The localized time represents using the time:Civil record. It includes the following details:
- date
- time
- timezone information
- daylight time-saving information
Time zone
The time zone can be obtained using a given zone ID or load the system time zone.
// Obtain the time zone corresponding to a given time zone ID. time:Zone? zone = time:getZone("Asia/Colombo"); // Obtain the system time zone. time:Zone zone = check time:loadSystemZone();
APIs
Parallel to the aforementioned time representations, this module includes a set of APIs to facilitate time conversions and manipulations using a set of high-level APIs. Those conversion APIs can be listed as follows.
The string representations of UTC
// Converts from RFC 3339 timestamp to UTC. time:Utc utc = check time:utcFromString("2007-12-03T10:15:30.00Z"); // Converts a given `time:Utc` time to a RFC 3339 timestamp. string utcString = time:utcToString(utc);
The string representations of civil
// Converts from RFC 3339 timestamp to a civil record. time:Civil civil2 = check time:civilFromString("2007-12-03T10:15:30.00Z"); // Converts a given `time:Civil` time to a RFC 3339 timestamp. string civilString = check time:civilToString(civil);
UTC value manipulation
// Returns the UTC time that occurs seconds after the given UTC. time:Utc utc = time:utcAddSeconds(time:utcNow(), 20.900); // Returns the difference in seconds between two given UTC time values. time:Utc utc1 = time:utcNow(); time:Utc utc2 = check time:utcFromString("2021-04-12T23:20:50.520Z"); time:Seconds seconds = time:utcDiffSeconds(utc1, utc2);
UTC vs civil
// Converts a given UTC to a Civil. time:Civil civil = time:utcToCivil(utc); // Converts a given Civil to a UTC. time:Utc utc = time:utcFromCivil(civil);
Functions
civilAddDuration
Adds the given time duration to the specified civil record. This is a time zone-agnostic operation and assumes that all days have exactly 86,400 seconds.
time:Civil civil = check time:civilFromString("2025-04-25T10:15:30.00Z"); time:Civil|time:Error updatedCivil = time:civilAddDuration(civil, {years: 1, days: 3, hours: 4, seconds: 6});
civilFromEmailString
Converts a given RFC 5322 formatted string (e.g., Wed, 10 Mar 2021 19:51:55 -0800 (PST)) to a civil record.
time:Civil|time:Error emailDateTime = time:civilFromEmailString("Wed, 10 Mar 2021 19:51:55 -0820");
Parameters
- dateTimeString string - The RFC 5322 formatted string to be converted (e.g.,
Wed, 10 Mar 2021 19:51:55 -0800 (PST))
civilFromString
Converts a given RFC 3339 timestamp(e.g., 2007-12-03T10:15:30.00Z) to a civil value.
time:Civil|time:Error civil1 = time:civilFromString("2021-04-12T23:20:50.520+05:30[Asia/Colombo]"); time:Civil|time:Error civil2 = time:civilFromString("2007-12-03T10:15:30.00Z");
Parameters
- dateTimeString string - The RFC 3339 timestamp as a string (e.g.,
2007-12-03T10:15:30.00Z).
civilToEmailString
function civilToEmailString(Civil civil, HeaderZoneHandling zoneHandling) returns string|ErrorConverts a given civil record to RFC 5322 format (e.g Wed, 10 Mar 2021 19:51:55 -0800 (PST)).
time:Civil civil = check time:civilFromString("2021-04-12T23:20:50.520+05:30[Asia/Colombo]"); string|time:Error emailDateTime = time:civilToEmailString(civil, time:PREFER_ZONE_OFFSET);
Parameters
- civil Civil - The
time:Civilrecord to be converted
- zoneHandling HeaderZoneHandling - Specifies how to handle the zone. Possible values include:
PREFER_ZONE_OFFSET: Use the zone offset for the output.PREFER_TIME_ABBREV: Use the time abbreviation for the output.ZONE_OFFSET_WITH_TIME_ABBREV_COMMENT: Use the zone offset and include the time abbreviation as a comment.
civilToString
Converts a given civil value to an RFC 3339 timestamp (e.g., 2021-03-05T00:33:28.839564+05:30).
time:Civil civil = check time:civilFromString("2007-12-03T10:15:30.00Z"); string|time:Error civilString = time:civilToString(civil);
Parameters
- civil Civil - The civil value to be converted
dateValidate
Validates whether the given date is within the range of Gregorian calendar rules.
time:Date date = {year: 1994, month: 11, day: 7}; time:Error? isValid = time:dateValidate(date);
Parameters
- date Date - The date to be validated
Return Type
- Error? -
()if thedateis valid or elsetime:Error
dayOfWeek
Gets the day of week for a specified date.
time:Date date = {year: 1994, month: 11, day: 7}; time:DayOfWeek day = time:dayOfWeek(date);
Parameters
- date Date - The date for which the day of the week is to be calculated
Return Type
- DayOfWeek - The
time:DayOfWeekif the date is valid or else panic
getZone
Returns the time zone object for a given zone ID.
time:Zone? zone = time:getZone("Asia/Colombo");
Parameters
- id string - Time zone ID in the format of ("Continent/City")
Return Type
- Zone? - Corresponding time zone object or
nilif the zone ID is invalid or not found.
loadSystemZone
Loads the default time zone of the system.
time:Zone|time:Error zone = time:loadSystemZone();
monotonicNow
function monotonicNow() returns decimalReturns the number of seconds from an unspecified epoch. This API guarantees consistent value increase in subsequent calls with nanoseconds precision.
decimal seconds = time:monotonicNow();
Return Type
- decimal - The number of seconds from an unspecified epoch
utcAddSeconds
Returns UTC time that occurs seconds after the given UTC time. This assumes that all days have 86400 seconds except when UTC represents a time during a positive leap second, in which case the corresponding day will be assumed to have 86401 seconds.
time:Utc utc = time:utcAddSeconds(time:utcNow(), 20.900);
Parameters
- utc Utc - The UTC time as a tuple
[int, decimal], where the first element is the seconds from the epoch and the second element is the fractional part of the last second.
- seconds Seconds - Number of seconds to be added. Can include fractional seconds (e.g., 20.900).
Return Type
- Utc - The resulting UTC time as a tuple
[int, decimal]after adding the specified seconds.
utcDiffSeconds
Returns difference in seconds between two UTC times.
This will be positive if utc1 occurs after utc2
time:Utc utc1 = time:utcNow(); time:Utc utc2 = check time:utcFromString("2021-04-12T23:20:50.520Z"); time:Seconds seconds = time:utcDiffSeconds(utc1, utc2);
Parameters
- utc1 Utc - 1st UTC time as a tuple
[int, decimal], where the first element is the seconds from the epoch and the second element is the fractional part of the last second.
- utc2 Utc - 2nd UTC time as a tuple
[int, decimal], where the first element is the seconds from the epoch and the second element is the fractional part of the last second.
Return Type
- Seconds - The difference between two UTC times in seconds
utcFromCivil
Converts a given civil value to a UTC timestamp.
time:Civil civil = time:utcToCivil(time:utcNow()); time:Utc utc = time:utcFromCivil(civil);
Parameters
- civilTime Civil - The civil value to be converted
utcFromString
Converts an RFC 3339 timestamp (e.g., 2007-12-03T10:15:30.00Z) to UTC.
time:Utc|time:Error utc = time:utcFromString("2007-12-03T10:15:30.00Z");
Parameters
- timestamp string - The RFC 3339 timestamp as a string (e.g.,
2007-12-03T10:15:30.00Z)
utcNow
Returns the time:Utc representing the current time (current instant of the system clock in seconds from the epoch of 1970-01-01T00:00:00).
time:Utc utc = time:utcNow();
Parameters
- precision int? (default ()) - Specifies the number of zeros after the decimal point (e.g., 3 would give the millisecond precision and nil means native precision (nanosecond precision 9) of the clock)
Return Type
- Utc - The
time:Utcvalue corresponding to the current UTC time
utcToCivil
Converts a given UTC timestamp to a civil value.
time:Utc utc = time:utcNow(); time:Civil civil = time:utcToCivil(utc);
Parameters
- utc Utc - The UTC time as a tuple
[int, decimal], where the first element is the seconds from the epoch and the second element is the fractional part of the last second.
Return Type
- Civil - The corresponding
time:Civilvalue
utcToEmailString
function utcToEmailString(Utc utc, UtcZoneHandling zh) returns stringConverts a given UTC to an email-formatted string (e.g Mon, 3 Dec 2007 10:15:30 GMT).
time:Utc utc = time:utcNow(); string emailFormattedString = time:utcToEmailString(utc);
Parameters
- utc Utc - The UTC time as a tuple
[int, decimal], where the first element is the seconds from the epoch and the second element is the fractional part of the last second.
- zh UtcZoneHandling (default "0") - Specifies the type of the zone value to be added. Possible values include:
"0": Default zone handling"GMT": Represents Greenwich Mean Time"UT": Represents Universal Time"Z": Represents the Zulu time zone (UTC+0)
Return Type
- string - The corresponding email-formatted string value
utcToString
Converts a given UTC time to an RFC 3339 timestamp (e.g., 2007-12-03T10:15:30.00Z).
string utcString = time:utcToString(time:utcNow());
Parameters
- utc Utc - The UTC time as a tuple
[int, decimal], where the first element is the seconds from the epoch and the second element is the fractional part of the last second.
Return Type
- string - The corresponding RFC 3339 timestamp string
Classes
time: TimeZone
Localized time zone implementation to handle time zones.
Constructor
Initializes a TimeZone object using a zone ID or the system default time zone.
init (string? zoneId)- zoneId string? () - Zone ID as a string or nil to initialize a TimeZone object with the system default time zone
fixedOffset
function fixedOffset() returns ZoneOffset?Returns the fixed zone offset if the time zone is always at a fixed offset from UTC; otherwise, returns nil.
Return Type
- ZoneOffset? - The fixed zone offset or nil
utcFromCivil
Converts a given civil record to a UTC timestamp based on the time zone value.
Parameters
- civil Civil - The civil record to be converted
utcToCivil
Converts a given UTC timestamp to a civil record based on the time zone value.
Parameters
- utc Utc - The UTC timestamp value to be converted
Return Type
- Civil - The corresponding civil record
civilAddDuration
Adds the given time duration to the specified civil date-time based on the time zone. The operation assumes that all days have exactly 86,400 seconds.
time:TimeZone timeZone = check new("Asia/Colombo"); time:Civil civil = check time:civilFromString("2025-04-25T10:15:30.00Z"); time:Civil|time:Error updatedCivil = timeZone.civilAddDuration(civil, {years: 1, days: 3, hours: 4});
Parameters
- civil Civil - The civil time to which the duration should be added
- duration Duration - The date-time duration to be added
Fields
- Fields Included from *readonly &
- readonly
Constants
Enums
time: HeaderZoneHandling
Indicates how to handle both zoneOffset and timeAbbrev.
Members
zoneOffset and timeAbbrev are presentzoneOffset and timeAbbrev are presentVariables
time: Z
The Z zone with hours: 0 and minutes: 0.
Records
time: Civil
Time within a region relative to a time scale stipulated by civilian authorities.
Fields
- year int - Year as an integer.
- month int - Month as an integer (1 <= month <= 12).
- day int - Day as an integer (1 <= day <= 31).
- anydata... -
- hour int - Hour as an integer (0 <= hour <= 23).
- minute int - Minute as an integer (0 <= minute <= 59).
- second Seconds - Second as a decimal value with nanoseconds precision.
- anydata... -
- utcOffset? ZoneOffset - An optional zone offset
- timeAbbrev? string - If present, abbreviation for the local time (e.g., EDT, EST) in effect at the time represented by this record; this is quite the same as the name of a time zone one time zone can have two abbreviations: one for standard time and one for daylight savings time
- which? ZERO_OR_ONE - when the clocks are put back at the end of DST, one hour's worth of times occur twice i.e. the local time is ambiguous this says which of those two times is meant same as fold field in Python see https://www.python.org/dev/peps/pep-0495/ is_dst has similar role in struct tm, but with confusing semantics
- dayOfWeek? DayOfWeek - Day of the week (e.g., SUNDAY, MONDAY, TUESDAY, ... SATURDAY)
time: Date
A date in the proleptic Gregorian calendar.
Fields
- year int - Year as an integer.
- month int - Month as an integer (1 <= month <= 12).
- day int - Day as an integer (1 <= day <= 31).
- anydata... -
- hour int - Hour as an integer (0 <= hour <= 23).
- minute int - Minute as an integer (0 <= minute <= 59).
- second Seconds - Second as a decimal value with nanoseconds precision.
- anydata... -
- utcOffset? ZoneOffset - Optional zone offset
time: Duration
Time duration used to adjust a civil date-time value by a specified amount. The duration can be added to or subtracted from the civil time. Fields in the record can be negative, in which case the duration is subtracted.
Fields
- years int(default 0) - The duration in years.
- months int(default 0) - The duration in months.
- weeks int(default 0) - The duration in weeks.
- days int(default 0) - The duration in days.
- hours int(default 0) - The duration in hours.
- minutes int(default 0) - The duration in minutes.
- seconds Seconds(default 0.0) - The duration in seconds.
time: TimeOfDay
Time within a day. Not always as a duration from midnight.
Fields
- year int - Year as an integer.
- month int - Month as an integer (1 <= month <= 12).
- day int - Day as an integer (1 <= day <= 31).
- anydata... -
- hour int - Hour as an integer (0 <= hour <= 23).
- minute int - Minute as an integer (0 <= minute <= 59).
- second Seconds - Second as a decimal value with nanoseconds precision.
- anydata... -
- utcOffset? ZoneOffset - Optional zone offset
time: ZoneOffset
Time zone offset.
Constraints:
- If any of the fields (
hours,minutes,seconds) are > 0, then all must be >= 0. - If any of the fields are < 0, then all must be <= 0.
Fields
- hours int - The hour offset as an integer
- minutes int(default 0) - The minute offset as an integer (default is 0)
- seconds? decimal - IETF zone files have historical zones that are offset by integer seconds; we use Seconds type so that this is a subtype of Delta
Errors
time: Error
Represents a generic module-level error.
time: FormatError
An error to be returned when arguments are invalid.
Object types
time: Zone
Abstract object representation to handle time zones.
fixedOffset
function fixedOffset() returns ZoneOffset?Returns the fixed zone offset if the time zone is always at a fixed offset from UTC; otherwise, returns nil.
Return Type
- ZoneOffset? - The fixed zone offset or nil
utcFromCivil
Converts a given civil record to a UTC timestamp based on the time zone value.
Parameters
- civil Civil - The civil record to be converted
utcToCivil
Converts a given UTC timestamp to a civil record based on the time zone value.
Parameters
- utc Utc - The UTC time as a tuple
[int, decimal], where the first element is the seconds from the epoch and the second element is the fractional part of the last second.
Return Type
- Civil - The corresponding civil record
civilAddDuration
Adds the given time duration to the specified civil date-time based on the time zone. The operation assumes that all days have exactly 86,400 seconds.
Union types
time: DayOfWeek
DayOfWeek
Day of the week according to the US convention, starting on Sunday.
time: ZERO_OR_ONE
ZERO_OR_ONE
Type that can be either zero or one.
time: UtcZoneHandling
UtcZoneHandling
Default zone value in different formats.
Intersection types
time: Utc
Utc
Point on UTC time-scale.
This is represented by a tuple of length 2.
The tuple is an ordered type and so the values can be
compared using the Ballerina <, <=, >, >= operators.
The first member of the tuple is int representing an integral number of
seconds from the epoch.
Epoch is the traditional UNIX epoch of 1970-01-01T00:00:00Z.
The second member of the tuple is a decimal giving the fraction of
a second.
For times before the epoch, n is negative and f is
non-negative. In other words, the UTC time represented
is on or after the second specified by n.
Leap seconds are handled as follows. The first member
of the tuple ignores leap seconds: it assumes that every day
has 86400 seconds. The second member of the tuple is >= 0.
and is < 1 except during positive leaps seconds in which it
is >= 1 and < 2. So given a tuple [n,f] after the epoch,
n / 86400 gives the day number, and (n % 86400) + f gives the
time in seconds since midnight UTC (for which the limit is
86401 on day with a positive leap second).
Decimal types
time: Seconds
Seconds
Holds the seconds as a decimal value.
Import
import ballerina/time;Metadata
Released date: about 15 hours ago
Version: 2.8.2
License: Apache-2.0
Compatibility
Platform: java21
Ballerina version: 2201.12.0
GraalVM compatible: Yes
Pull count
Total: 1350520
Current verison: 381
Weekly downloads
Keywords
time
utc
epoch
civil
Type/Library
Area/Built-in
Name/Time
Contributors