2
votes

How can I get the current hour from a linux timestamp? I can get the year, month, day, minute, and second, but not the hour. Any help?

Current code:

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)

Broken:

local hours = math.floor((secondsPassed % 86400) / 3600)-- +1
2
If your days is correct, then how can your hours/minutes/seconds be broken since they all rely on secondsPassed?RonaldBarzell
The only one broken is hoursmlnlover11

2 Answers

4
votes

There are several issues here:

  • UNIX time is relative to midnight 1970-01-01, GMT. If you are not in GMT, you will see an offset that depends on your time zone. If your region observes daylight savings time, this offset will vary based on the date in a potentially rather complex fashion.

  • Years are not 365.25 days long. They are either 365 or 366 days long, based on the year. (Which doesn't even average out to 365.25; due to special cases for years divisible by 100 and 400, it averages out to 365.2425.)

Unless there is some reason that you cannot use the Lua date and time modules, I would strongly recommend that you do so, rather than trying to recreate them yourself.

0
votes

You were super close. I hours correct so far by:

local hours = math.floor((secondsPassed % 86400) / 1440) + 1