Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Back and forth UTC dates in lua

Tags:

date

utc

lua

I'm having problems converting a lua date to a timestamp and then obtaining back the original date from it. It does work for non UTC dates, but not with UTC.

Currently my example code is:

local dt1 = os.date( "*t" );
print( dt1.hour );

local dt2 = os.date( "*t", os.time( dt1 ) );
print( dt2.hour );

print( "-=-=-" );

local dt1 = os.date( "!*t" );
print( dt1.hour );

local dt2 = os.date( "!*t", os.time( dt1 ) );
print( dt2.hour );

local dt2 = os.date( "*t", os.time( dt1 ) );
print( dt2.hour );

Which yields the output:

12
12
-=-=-
10
9
11

So, in the second part, after obtaining the timestamp using os.time( os.date( "!*t" ) ); I don't know how to obtain the original date back. What is it that I'm doing wrong?

like image 276
Javier Mr Avatar asked Jun 19 '26 08:06

Javier Mr


1 Answers

Working with "date tables" in Lua

Let dt be a "date table".
For example, a value returned by os.date("*t") is a "date table".


How to normalize "date table"
For example, after adding 1.5 hours to the current time
local dt = os.date("*t"); dt.min = dt.min + 90
you need to normalize the table fields.

function normalize_date_table(dt)
   return os.date("*t", os.time(dt))
end

This function returns new date table which is equivalent to its argument dt regardless of the meaning of content of dt: whether it contains local or GMT time.


How to convert Unix time to "local date table"

dt = os.date("*t", ux_time)

How to convert Unix time to "GMT date table"

dt = os.date("!*t", ux_time)

How to convert "local date table" to Unix time

ux_time = os.time(dt)

How to convert "GMT date table" to Unix time

-- for this conversion we need precalculated value "zone_diff"
local tmp_time = os.time()
local d1 = os.date("*t",  tmp_time)
local d2 = os.date("!*t", tmp_time)
d1.isdst = false
local zone_diff = os.difftime(os.time(d1), os.time(d2))
-- zone_diff value may be calculated only once (at the beginning of your program)

-- now we can perform the conversion (dt -> ux_time):
dt.sec = dt.sec + zone_diff
ux_time = os.time(dt)
like image 98
Egor Skriptunoff Avatar answered Jun 21 '26 05:06

Egor Skriptunoff