Last active
September 1, 2023 17:49
-
-
Save thomo/8ac2bceb6400eb8868c651e8897be958 to your computer and use it in GitHub Desktop.
Convert from human readable date/time to epoch timestamp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- The MIT License (MIT) | |
-- Copyright (c) 2018,2020 Thomas Mohaupt <thomas.mohaupt@gmail.com> | |
-- year: 2-digit (means 20xx) or 4-digit (>= 2000) | |
function datetime2epoch(second, minute, hour, day, month, year) | |
local mi2sec = 60 | |
local h2sec = 60 * mi2sec | |
local d2sec = 24 * h2sec | |
-- month to second, without leap year | |
local m2sec = { | |
0, | |
31 * d2sec, | |
59 * d2sec, | |
90 * d2sec, | |
120 * d2sec, | |
151 * d2sec, | |
181 * d2sec, | |
212 * d2sec, | |
243 * d2sec, | |
273 * d2sec, | |
304 * d2sec, | |
334 * d2sec } | |
local y2sec = 365 * d2sec | |
local offsetSince1970 = 946684800 | |
local yy = year < 100 and year or year - 2000 | |
local leapCorrection = math.floor(yy/4) + 1 | |
if (yy % 4) == 0 and month < 3 then | |
leapCorrection = leapCorrection - 1 | |
end | |
return offsetSince1970 + | |
second + | |
minute * mi2sec + | |
hour * h2sec + | |
(day - 1) * d2sec + | |
m2sec[month] + | |
yy * y2sec + | |
leapCorrection * d2sec | |
end | |
-- datetime2epoch(11,12,13,7,9,20) | |
-- 1599484331 | |
-- datetime2epoch(11,12,13,7,9,2020) | |
-- 1599484331 |
datetime2epoch(11,12,13,7,9,2020)
does not lead to a UNIX timestamp reflecting Sept. 7th, 2020 13:12:11 but instead64714684331
which is
09/22/4020 @ 1:12pm (UTC). Test on nodemcu-firmware 3.0.0.0 with Lua 5.1.4.
So it seems to be off 2000 years + 15 days in this example.
Thanks for your feedback - it was mentioned to be used with 2-digit years (since 2000). I have changed it to also accept 4-digit years now.
Hello, thank you very much for the very quick fix! I can confirm that it works now as expected. Awesome! 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
datetime2epoch(11,12,13,7,9,2020)
does not lead to a UNIX timestamp reflecting Sept. 7th, 2020 13:12:11 but instead64714684331
which is09/22/4020 @ 1:12pm (UTC). Test on nodemcu-firmware 3.0.0.0 with Lua 5.1.4.
So it seems to be off 2000 years + 15 days in this example.