How to get local time as a formatted string in Lua

10,322

os.date is the function you are looking for. Its first optional parameter, format, does what you want:

os.date('%Y-%m-%d %H:%M:%S')
--> 2019-04-02 10:50:52

From the Lua 5.3 manual on os.date:

os.date ([format [, time]])

Returns a string or a table containing date and time, formatted according to the given string format.

If format starts with '!', then the date is formatted in Coordinated Universal Time.

If format is not "*t", then date returns the date as a string, formatted according to the same rules as the ISO C function strftime.

You can learn more about the formatting rules of C's strftime here.

In case you don't get your local time for whatever reason you can simply add the required offset.

local timeShift = 3 * 60 * 60  -- +3 hours
os.date('%Y-%m-%d %H:%M:%S', os.time() + timeShift)
--> 2019-04-02 18:24:15 for 15:24:15 UTC
Share:
10,322

Related videos on Youtube

BruAPAHE
Author by

BruAPAHE

Back-end dev (Gismeteo)

Updated on June 04, 2022

Comments

  • BruAPAHE
    BruAPAHE almost 2 years

    I need a date time string formatted as %Y-%m-%d %H:%M:%S.

    I can't figure out how to use Lua's standard functions os.date() and os.time() to achieve that.

  • BruAPAHE
    BruAPAHE about 5 years
    os.date('%Y-%m-%d %H:%M:%S') it's UTC time. I need LOCALTIME
  • cfillion
    cfillion about 5 years
    os.date gives the system's local time unless format starts with a !. There might be some other reason why it returns UTC for you. Which platform are you on, and is the system time and timezone set appropriately? You can check out Lua's os.time's implementation here: github.com/lua/lua/blob/…
  • Piglet
    Piglet about 5 years
    if you have to provide an offset to that library, you can as well just use os.date() with an offset...