Skip to content

Instantly share code, notes, and snippets.

@dnmellen
Last active December 24, 2015 07:19
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 dnmellen/6762652 to your computer and use it in GitHub Desktop.
Save dnmellen/6762652 to your computer and use it in GitHub Desktop.
Returns an array of dates between two given dates. You can select the "step" (year, month, day)
-- Returns an array of dates between `date1` and `date2`
-- The 'step' between dates it can be selected with 3 possible values:
-- (year, month, day)
--
-- ie: get_interval_dates(20130101, 20130601, "month")
-- -> (201301, 201302, 201303, 201304, 201305, 201306)
--
-- Diego Navarro (dnmellen)
function get_interval_dates(date1, date2, step)
local result = {}
local i = 1
local date1_time = os.time({year=string.sub(date1, 1, 4), month=string.sub(date1, 5, 6), day=string.sub(date1, 7, 8)})
local date2_time = os.time({year=string.sub(date2, 1, 4), month=string.sub(date2, 5, 6), day=string.sub(date2, 7, 8)})
local step_int = nil
local step_fmt = nil
if step == "day" then
step_int = 86400
step_fmt = "%Y%m%d"
elseif step == "month" then
step_int = 2678400
step_fmt = "%Y%m"
elseif step == "year" then
step_int = 31536000
step_fmt = "%Y%m"
else
return result
end
local date_aux = date1_time
while date_aux < date2_time + step_int do
result[i] = os.date(step_fmt, date_aux)
date_aux = date_aux + step_int
i = i + 1
end
return result
end
for i, line in ipairs(get_interval_dates("20130101", "20130601", "month")) do
print(line)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment