i need a loop where x
and y
are two input variable,
now I want to get a resulting array in which all period between these two dates are breakup in months.
For example, x = 1.1.2019
and y = 31.3.2019
,
result would be array like
1.1.2019, 31.1.2019, 1.2.2019, 28.2.2019, 1.3.2019, 31.3.2019
using LUA programming language.
Asked
Active
Viewed 61 times
-1

Adnan Sharif
- 1
- 1
1 Answers
2
x = os.time{year=2019, month=1, day=1}
y = os.time{year=2019, month=3, day=31}
df = {}
i = 2
sec_day = 24*60*60
df[1] = x
while x <= y do
x = x +sec_day
df[i] = x
i = i+1
end
--loop to get unique months
hash={}
d_months = {}
for _,v in ipairs(df) do
if (not hash[os.date('%m',v)]) then
d_months[#d_months+1] = os.date('%m', v)
hash[os.date('%m',v)] = true
end
end
--now everything is set up and we can iterate over the months to get the start and end days of the month
min_d = {}
max_d = {}
for idx,month in ipairs(d_months) do
min = nil
max = nil
for _,v in ipairs(df) do
if os.date('%m', v) == month then
min = min or v
max = max or v
min = min < v and min or v
max = max > v and max or v
end
end
min_d[idx] = os.date('%d.%m.%Y', min)
max_d[idx] = os.date('%d.%m.%Y', max)
print(os.date('%d.%m.%Y', min) .. " " .. os.date('%d.%m.%Y', max))
end
A short explanation beyond the commentaries. First we get a table of each date between (and including) start and end date. In the next loop we are looking for an array of unique months (see Lua : remove duplicate elements). And finally we iterate over the array of all dates and find minimum and maximum for each month.
Output
01.01.2019 31.01.2019
01.02.2019 28.02.2019
01.03.2019 31.03.2019
If you want to have it for years to, just do 2 extra loops. Once you need to find the unique years and then you need to compare not only for months but also for years in the last part.
Edit: changed format of output format.

pythonic833
- 3,054
- 1
- 12
- 27
-
I got this output 01/01/19 01/31/19 02/01/19 02/28/19 03/01/19 03/31/19 04/01/19 04/01/19 – Adnan Sharif Feb 02 '19 at 05:11
-
That is due to the standard formatting of lua. The timestamps are correct. If you want to have the output you desire, just write one more loop to put everything in correct order – pythonic833 Feb 02 '19 at 08:02
-
1instead of putting format as `%x` use `%d.%m.%Y` to get the desired format – Nifim Feb 02 '19 at 14:53