Post your best Lua script examples here

User avatar
By Manudax
#10318 Hi all,
newbie with LUA and ESP8266 I try to use date and timestamp without any RTC external hardware clock.
This function combinated with getting ntp date from internet and tmr.now() can be use to have an on time internal RTC.
I create a simple function to return a timestamp when passing year,month,day,hour,minute,second.
I'm actually working on the reverse function to have a human comprehensive date displayed on a web page but faced to severals issues.
May be a Javascript function can be use directly in the web page to convert timestamp to date when receiving data from the ESP8266.

Code: Select allfunction datetotstp(year,month,day,hour,minute,second)
local leap = 0

local t_month = {0,31,59,90,120,151,181,212,243,273,304,334}
local t_leapyear = {72,76,80,84,88,92,96,00,04,08,12,16,20,24,28,32,36}
local sum_year = 0

function get_leapyear(year)
   for key,value in pairs(t_leapyear) do
      if (value + 1900) == year then return 1 end
   end   
   for key,value in pairs(t_leapyear) do
      if (value + 2000) == year then return 1 end
   end   
return nil
end

-- date validation
if year < 1970 or year > 2038 then
   return nil
elseif month < 1 or month > 12 then
   return nil
elseif hour < 1 or hour > 23 then
   return nil
elseif minute < 1 or minute > 59 then
   return nil
elseif second < 1 or second > 59 then
   return nil
end
-- day validation
if day > 28 and get_leapyear(year) == nil then
   return nil
end
if day > 29 then return nil end

-- year to timestamp
for y = 1971,year do
   sum_year = sum_year + 31536000
if    get_leapyear(y) ~= nil then sum_year = sum_year + 86400 end
end

-- month to timestamp
sum_month = (t_month[month]*86400)

-- total timestamp
tsp = sum_year + sum_month + ((day-1)*86400) + hour*3600 + minute*60 + second

return tsp
end

Don't hesitate to improve this code to have more compacity or functionality.