Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting UTC UNIX timestamp in Lua

An API returns a timestamp as UNIX timestamp at UTC and I would like to know if this timestamp was more than x seconds ago. As expected, this works fine with os.time() - x > timestamp in UTC, but blows up in other timezones.

Unfortunately I can't find a good way solve this in lua.

os.date helpfully has the ! prefix (e.g. os.date("!%H:%M:%S")) to return time at UTC, but it seems that despite the documentation stating it supports all strftime options, this does not support the %s option. I have heard people mention that this is caused by Lua compile time options for a similar issue, but changing these is not possible as the interpreter is provided by the user.

like image 578
Azsgy Avatar asked May 08 '17 20:05

Azsgy


People also ask

Is timestamp stored in UTC?

Timestamps are generally stored in UTC so the conversion for display to other timezones is easier and possible.

Is UNIX timestamp in UTC?

Unix time is a way of representing a timestamp by representing the time as the number of seconds since January 1st, 1970 at 00:00:00 UTC. One of the primary benefits of using Unix time is that it can be represented as an integer making it easier to parse and use across different systems.

How do you find the UTC timestamp in Unix?

Use the getTime() method to get a UTC timestamp, e.g. new Date(). getTime() . The method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation. Calling the method from any time zone returns the same UTC timestamp.


2 Answers

You can use

os.time(os.date("!*t"))

to get the current UNIX epoch.

like image 89
Joe Avatar answered Sep 20 '22 10:09

Joe


Ok, so you want the UTC time. Keep in mind that os.time actually knows nothing about timezones, so for example:

os.time(os.date("!*t"))
  1. Will get UTC time and populate table struct.
  2. Will convert table struct according to current timezone to unix timestamp.

So you actually would get your UNIX_TIME - TIMEZONE_OFFSET. If you are in GMT+5 you will get timestamp at UTC-5.

The correct way to do time conversion in lua is:

os.time() -- get current epoch value
os.time{ ... } -- get epoch value for local date/time values
os.date("*t"),os.date("%format") -- get your local date/time
os.date("!*t") or os.date("!%format") -- get UTC date/time
os.date("*t", timestamp),os.date("%format", timestamp) -- get your local date/time for given timestamp
os.date("!*t", timestamp) or os.date("!%format", timestamp) -- get UTC date/time for given timestamp

Kudos to Mons at https://gist.github.com/ichramm/5674287.

If you really need to convert any UTC date to timestamp, there's a good description on how to do this in this question: Convert a string date to a timestamp

like image 23
kworr Avatar answered Sep 21 '22 10:09

kworr