简体   繁体   中英

Breakup of months between two Dates

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM