方案一:先获取下个月1号时间戳,减去一天秒数,再获取day
local year = os.date("%Y")
local month = os.date("%m") + 1
if month > 12 thenmonth = 1year = year + 1
end
local timestamp = os.time({year = year, month = month, day = 1}) - 86400
local date = os.date("!*t", timestamp)
print("这个月的最大天数是:" .. date.day)
方案二:算闰年
- 当涉及到月份的天数时,通常情况下,只有二月份的天数是不固定的,可能是28天或29天。其他月份的天数是固定的。
local year = os.date("%Y")
local month = os.date("%m")
local daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
}
if year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0) thendaysInMonth[2] = 29
endlocal maxDays = daysInMonth[tonumber(month)]
print("这个月的最大天数是:" .. maxDays)
换一种写法
local function getMaxDayOfMonth(year, month)local maxDay = 31if month == 2 thenif year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0) thenmaxDay = 29elsemaxDay = 28endelseif month == 4 or month == 6 or month == 9 or month == 11 thenmaxDay = 30endreturn maxDay
endlocal year = 2023
local month = 11
local maxDay = getMaxDayOfMonth(year, month)
print(maxDay)