Skip to content

Instantly share code, notes, and snippets.

@Tyxz
Last active February 16, 2020 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tyxz/97d30df02f47fe2a6616ead45a4fe88d to your computer and use it in GitHub Desktop.
Save Tyxz/97d30df02f47fe2a6616ead45a4fe88d to your computer and use it in GitHub Desktop.
Calculate the week day in pure Lua. Only depends on the math package to floor numbers.
--[[----------------------------------------
Project: LibClockTST
Author: Arne Rantzen (Tyx)
Created: 2020-02-16
License: GPL-3.0
----------------------------------------]]--
--- Get the day of the week by the guassian algorithm
--@param table should be containing three ints: year, month, day
--@return weekday number after ISO norm from 1 = Monday to 7 = Sunday
--@see https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Gauss's_algorithm
local function GetGaussWeekDay(table)
assert(type(table.year) == "number" and type(table.month) == "number" and type(table.day) == "number",
"Please provide a table like {year = 2020, month = 2, number = 16}")
local function GetDaysFromZero(y)
local leaps = math.floor(y / 4) - math.floor( y / 100) + math.floor(y / 400)
return 365 * y + leaps
end
local mm = (table.month % 12 + 9) % 12 -- End is February (11), start is March (0)
local dd = GetDaysFromZero(table.year + math.floor(table.month / 12) - math.floor(mm / 10))
local totalDays = dd + math.floor((mm*306 + 5)/10) + table.day - 307
return (totalDays) % 7 + 1 -- shift monday to 1st and sunday to 7th
end
--- Get the day of the week by the disperate algorithm
--@param table should be containing three ints: year, month, day
--@return weekday number after ISO norm from 1 = Monday to 7 = Sunday
--@see https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Disparate_variation
local function GetDisparateWeekDay(table)
assert(type(table.year) == "number" and type(table.month) == "number" and type(table.day) == "number",
"Please provide a table like {year = 2020, month = 2, number = 16}")
if table.month < 3 then
table.year = table.year - 1
end
local y = table.year
local c = 0
if tostring(y):len() > 2 then
c = tonumber(tostring(y):sub(1, -3))
y = tonumber(tostring(y):sub(-2))
end
local d = table.day
local m = (table.month % 12 + 9) % 12 + 1
local w = (d + math.floor(2.6 * m - 0.2) + y + math.floor(y / 4) + math.floor(c / 4) - 2 * c) % 7
if w < 0 then
w = w + 7
end
return (w - 1) % 7 + 1 -- shift monday to 1st and sunday to 7th
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment