从Unix时间戳中获取小时数

我怎样从 Linux 时间戳中获得当前小时数?我可以获取年份、月份、日期、分钟和秒数,但是没有小时数。有什么方法可以解决吗?

当前代码:

local secondsPassed = os ~= nil and os.time() or tick()
local year = 1970 + math.floor(secondsPassed / (86400 * 365.25))
local days = math.floor((secondsPassed % (365.25 * 86400)) / 86400)
days = days + (year - 2011)
local minutes = math.floor((secondsPassed % 3600) / 60)
local seconds = math.floor(secondsPassed % 60)

修正后的代码:

local hours = math.floor((secondsPassed % 86400) / 3600)-- +1
点赞
用户88888888
用户88888888

以下存在一些问题:

  • UNIX 时间是相对于 GMT 的1970年1月1日午夜。如果你不在 GMT 时区,你会看到一个偏移量,取决于你所在的时区。如果你所在的地区使用夏令时,则该偏移量将根据日期可能以相当复杂的方式变化。

  • 年份并不是365.25天长,而是根据年份为365天或366天长。(这甚至不平均分配到365.25天;由于可被100和400整除的年份有特殊情况,平均分配为365.2425。)

除非有某些原因不能使用 Lua datetime 模块,我强烈建议你使用它们,而不是试图自己重新创建它们。

2012-12-21 21:57:13
用户4550963
用户4550963

你非常接近了。到目前为止,我正确的小时数为:

local hours = math.floor((secondsPassed % 86400) / 1440) + 1
2015-06-06 04:11:35