Search code examples
tarantool

What is the correct way to work with dates in Tarantool?


There are several ways to get time in Tarantool:

  • Using the clock module
  • Using fiber.time function
  • Using os.date

But what is the correct way to work with dates?


Solution

  • For the first, there are several routines for Unix epoch:

    1. os.time() — classic Lua time function. Kinda slow and not very efficient. Not recommended to use inside tarantool for getting current epoch, but of course will work. May be used for getting epoch of arbitrary date (within local timezone). ex:
    os.time({ year = 2020, month = 6, day = 4 })
    

    will produce 1591261200, which is 12:00:00 in my GMT+3 timezone

    1. clock.time() (and clock.time64()) — High resolution timer, almost raw binding to clock_gettime. More information may be taken from doc
    2. fiber.time() (and also fiber.time64()) — Cached version of clock.time. Updated every event loop iteration. Recommended for use if absolute precision of clock is not required.

    For converting epoch into different formats and timezones there are variants:

    1. os.date("<format>" [, epoch ]) — Convert epoch into local timezone.
    2. os.date("!<format>" [, epoch ]) (note ! prefix) — Convert epoch into GMT timezone.
    3. For getting components of a date as a table we may use os.date('*t') for local and os.date('!*t') for UTC
    4. icu-date may be considered it you need to work with different timezones and/or formats.

    For example, if you need UTC time, it's ok to use cached fiber.time with os.date:

    local fiber = require 'fiber'
    os.date("!%Y-%m-%dT%H:%M:%SZ", fiber.time())
    

    will return something like 2020-06-04T11:48:54Z independently on timezone