How to get local time as a formatted string in Lua
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
Related videos on Youtube
Comments
-
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()
andos.time()
to achieve that. -
BruAPAHE about 5 yearsos.date('%Y-%m-%d %H:%M:%S') it's UTC time. I need LOCALTIME
-
cfillion about 5 years
os.date
gives the system's local time unlessformat
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'sos.time
's implementation here: github.com/lua/lua/blob/… -
Piglet about 5 yearsif you have to provide an offset to that library, you can as well just use os.date() with an offset...