functions
Timecmp

timecmp Function

timecmp compares two timestamps and returns a number that represents the ordering of the instants those timestamps represent.

timecmp(timestamp_a, timestamp_b)
ConditionReturn Value
timestamp_a is before timestamp_b-1
timestamp_a is the same instant as timestamp_b0
timestamp_a is after timestamp_b1

When comparing the timestamps, timecmp takes into account the UTC offsets given in each timestamp. For example, 06:00:00+0200 and 04:00:00Z are the same instant after taking into account the +0200 offset on the first timestamp.

In the OpenTofu language, timestamps are conventionally represented as strings using RFC 3339 (opens in a new tab) "Date and Time format" syntax. timecmp requires the its two arguments to both be strings conforming to this syntax.

Examples

> timecmp("2017-11-22T00:00:00Z", "2017-11-22T00:00:00Z")
0
> timecmp("2017-11-22T00:00:00Z", "2017-11-22T01:00:00Z")
-1
> timecmp("2017-11-22T01:00:00Z", "2017-11-22T00:00:00Z")
1
> timecmp("2017-11-22T01:00:00Z", "2017-11-22T00:00:00-01:00")
0

timecmp can be particularly useful in defining custom condition checks that involve a specified timestamp being within a particular range. For example, the following resource postcondition would raise an error if a TLS certificate (or other expiring object) expires sooner than 30 days from the time of the "apply" step:

  lifecycle {
    postcondition {
      condition     = timecmp(timestamp(), timeadd(self.expiration_timestamp, "-720h")) < 0
      error_message = "Certificate will expire in less than 30 days."
    }
  }

Related Functions

  • timestamp returns the current timestamp when it is evaluated during the apply step.
  • timeadd can perform arithmetic on timestamps by adding or removing a specified duration.