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.
Timestamps are generally stored in UTC so the conversion for display to other timezones is easier and possible.
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.
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.
You can use
os.time(os.date("!*t"))
to get the current UNIX epoch.
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"))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With