Skip to content

Instantly share code, notes, and snippets.

@thomo
Last active September 1, 2023 17:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomo/8ac2bceb6400eb8868c651e8897be958 to your computer and use it in GitHub Desktop.
Save thomo/8ac2bceb6400eb8868c651e8897be958 to your computer and use it in GitHub Desktop.
Convert from human readable date/time to epoch timestamp
-- 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
@tricoos
Copy link

tricoos commented Feb 4, 2020

datetime2epoch(11,12,13,7,9,2020) does not lead to a UNIX timestamp reflecting Sept. 7th, 2020 13:12:11 but instead 64714684331 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.

@thomo
Copy link
Author

thomo commented Feb 4, 2020

datetime2epoch(11,12,13,7,9,2020) does not lead to a UNIX timestamp reflecting Sept. 7th, 2020 13:12:11 but instead 64714684331 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.

@tricoos
Copy link

tricoos commented Feb 4, 2020

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