Time in GDScript

GDScript offers support for times and durations. Here are some examples:

extends Node

func _ready():
    var p = funcref(self, "print_line")

    # We'll start by getting the current time.
    var now = OS.get_datetime()
    p.call_func(now)

    # You can build a time dictionary by providing the
    # year, month, day, etc. GDScript doesn't have a built-in
    # time zone concept, so we'll use UTC.
    var then = {
        "year": 2009,
        "month": 11,
        "day": 17,
        "hour": 20,
        "minute": 34,
        "second": 58
    }
    p.call_func(then)

    # You can extract the various components of the time
    # value as expected.
    p.call_func(then["year"])
    p.call_func(then["month"])
    p.call_func(then["day"])
    p.call_func(then["hour"])
    p.call_func(then["minute"])
    p.call_func(then["second"])

    # GDScript doesn't have built-in weekday calculation,
    # so we'll skip that part.

    # These methods compare two times, testing if the
    # first occurs before, after, or at the same time
    # as the second, respectively.
    p.call_func(is_date_before(then, now))
    p.call_func(is_date_after(then, now))
    p.call_func(is_date_equal(then, now))

    # GDScript doesn't have a built-in duration concept,
    # so we'll calculate the difference in seconds.
    var diff = time_difference(then, now)
    p.call_func(diff)

    # We can compute the length of the duration in
    # various units.
    p.call_func(diff / 3600.0)  # Hours
    p.call_func(diff / 60.0)    # Minutes
    p.call_func(diff)           # Seconds

    # You can use add_to_time to advance a time by a given
    # duration, or subtract to move backwards.
    p.call_func(add_to_time(then, diff))
    p.call_func(add_to_time(then, -diff))

func is_date_before(date1, date2):
    return OS.get_unix_time_from_datetime(date1) < OS.get_unix_time_from_datetime(date2)

func is_date_after(date1, date2):
    return OS.get_unix_time_from_datetime(date1) > OS.get_unix_time_from_datetime(date2)

func is_date_equal(date1, date2):
    return OS.get_unix_time_from_datetime(date1) == OS.get_unix_time_from_datetime(date2)

func time_difference(date1, date2):
    return OS.get_unix_time_from_datetime(date2) - OS.get_unix_time_from_datetime(date1)

func add_to_time(date, seconds):
    var unix_time = OS.get_unix_time_from_datetime(date) + seconds
    return OS.get_datetime_from_unix_time(unix_time)

This script demonstrates various time-related operations in GDScript. Note that GDScript doesn’t have as extensive built-in time functionality as some other languages, so we’ve had to implement some of these operations manually.

When you run this script, it will output various time-related information and comparisons. The exact output will depend on the current time when you run the script.

Next, we’ll look at the related idea of time relative to the Unix epoch.