function getYearByTimestamp(stamp)
stamp = stamp + 8 * 3600 -- 是从1970年1月1日8点0分0秒(UTC/GMT的午夜)开始计时,所经过的秒数
local day = math.floor(stamp / (24 * 60 * 60))
local year4 = math.floor(day / (365 * 3 + 366))
local remainDay = day % (365 * 3 + 366)
local year = 1970 + year4 * 4
local time = stamp - year4 * (365 * 3 + 366) * (24 * 60 * 60)
local text = ""
print(year, remainDay)
if remainDay < 365 then
text = getTime(time, false)
elseif remainDay < 2 * 365 then
year = year + 1
text = getTime(time - 365 * (24 * 60 * 60), false)
elseif remainDay < 2 * 365 + 366 then
year = year + 2
text = getTime(time - 2 * 365 * (24 * 60 * 60), true) -- 1972年是闰年
else
year = year + 3
text = getTime(time - (366 + 2 * 365) * (24 * 60 * 60), false)
end
return year .. "年" .. text
end
function getTime(time, isLeapYear)
local day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
if isLeapYear then
day[2] = 29
end
local remainday = math.floor(time / (24 * 60 * 60))
local month = 1
for i, v in pairs(day) do
if remainday > v then
month = month + 1
remainday = remainday - v
time = time - v * (24 * 60 * 60)
print("v = ", i, v, "remainday = ", remainday)
else
break
end
end
local day = math.floor(time / (24 * 60 * 60))
local remainSec = time % (24 * 60 * 60)
local hour = math.floor(remainSec / 3600)
local min = math.floor(remainSec % 3600 / 60)
local second = math.floor(remainSec % 60)
return month .. "月" .. (remainday + 1).. "日" .. hour .. "时" .. min .. "分" .. second.. "秒"
end
print(getYearByTimestamp(1583724930))
输出为
2020年3月9日11时35分30秒
注:加八小时其实就是时差的问题,标准时间是格林尼治时间,格林尼治时间要比东八区时间慢8个小时。