Skip to main content

Rego Built-in Function: time.format

time.format is Rego's built-in function that takes a time in nanoseconds since the Unix epoch and formats it as a string. This is useful for displaying timestamps in a human-readable format and presenting times in a given timezone.

The function accepts arguments in three formats, making it slightly more complicated to use. These are either:

  • A single value representing the nanoseconds since the Unix epoch

    time.format(1720021249361794300)
    time.format(1712345679361794300)
  • A two-element array consisting of:

    # Using a named timezone identifier
    time.format([1720021249361794300, "Europe/Paris"])
    # Using a timezone code
    time.format([1720021249361794300, "PDT"])
  • A three-element array consisting of:

    # Using time format constant
    time.format([1720021249361794300, "Europe/Paris", "RFC822Z"])
    # Using a custom time layout string
    time.format([1720021249361794300, "Europe/Paris", "2006_01_02_15_04_05"])

Examples

Show the local time in a response

time.format can be used to provide information to the user in a human-readable format in error messages. Error codes and local times can be useful when debugging or troubleshooting and so in many cases returning them from policy decisions can be helpful.

In this example we see a user is not an admin and is denied access, the policy response is a message that includes the current time and an error code to help them debug.

policy.rego
package play

import rego.v1

request_time := time.parse_ns(
"RFC822Z",
input.request_utc_time,
)

local_time := time.format([
request_time,
input.tz,
"15:04:05",
])

default allow := false

allow if count(reasons) == 0

reasons contains message if {
input.role != "admin"
message := sprintf("E123 %s", [local_time])
}
input.json
{
"user": "yamada-hanako@example.com",
"tz": "Asia/Tokyo",
"role": "developer",
"request_utc_time": "03 Jul 24 14:04 +0000"
}
data.json
{}

Open in OPA Playground

RuleOutput ValueNotes
allowfalseThe user is not an admin
reasons["E123 23:04:00"]This contains the error code and the local time