-- title:  utc
-- author: pixelbath
-- desc:   renders tstamp() as current UTC date/time. compact version could be more compacted, but it's at least semi-readable this way.

local days = {
    {   0,  31,  60,  91, 121, 152, 182, 213, 244, 274, 305, 335},
    { 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700},
    { 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065},
    {1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430},
}
function tstampToDateTime(epoch)
	local flr=math.floor
	epoch = tonumber(epoch)
    local dt = {}
    dt.second = epoch%60; epoch=epoch//60
    dt.minute = epoch%60; epoch=epoch//60
    dt.hour   = epoch%24; epoch=epoch//24

	local years,month = epoch//(365*4+1)*4,0
	epoch = epoch % (365*4+1)
    local year
    for y = 4,1,-1 do
        if epoch >= days[y][1] then
            year = y
			break
        end
    end

    for m = 12,1,-1 do
        if epoch >= days[year][m] then
            month = m
			break
        end
    end

    dt.year  = years+year+1970-1
    dt.month = month
    dt.day   = epoch-days[year][month]+1

    return string.format("%04d-%02d-%02d %02d:%02d:%02d", dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
end

function tstampToDT(epoch)
	local flr,ep,ly,dt=math.floor,epoch//1,365*4+1,{}
    dt.s=ep%60;ep=ep//60
    dt.m=ep%60;ep=ep//60
    dt.h=ep%24;ep=ep//24
	local yr,yrs,mo=0,ep//ly*4,0
	ep=ep%ly
    for y=4,1,-1 do
        if ep>=days[y][1]then yr=y;break end
    end
    for m=12,1,-1 do
        if ep>=days[yr][m]then mo=m;break end
    end
    dt.y=yrs+yr+1970-1
    dt.mo=mo
    dt.d=ep-days[yr][mo]+1
    return string.format("%04d-%02d-%02d %02d:%02d:%02d",dt.y,dt.mo,dt.d,dt.h,dt.m,dt.s)
end

function TIC()
	cls(0)
	local timestamp = tstamp()
	print("regular - 747 chars: "..tstampToDateTime(timestamp), 10, 10, 4,1,1,1)
	print("compact - 496 chars: "..tstampToDT(timestamp), 10, 20, 4,1,1,1)
end

-- <PALETTE>
-- 000:1a1c2c5d275db13e53ef7d57ffcd75a7f07038b76425717929366f3b5dc941a6f673eff7f4f4f494b0c2566c86333c57
-- </PALETTE>

