【lua】获取某月最大天数

方案一:先获取下个月1号时间戳,减去一天秒数,再获取day

-- 获取当前日期的年份和月份
local year = os.date("%Y")
local month = os.date("%m") + 1
if month > 12 then
    month = 1
    year = 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, -- 1月
    28, -- 2月
    31, -- 3月
    30, -- 4月
    31, -- 5月
    30, -- 6月
    31, -- 7月
    31, -- 8月
    30, -- 9月
    31, -- 10月
    30, -- 11月
    31  -- 12月
}

-- 如果是闰年,更新二月份的天数
if year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0) then
    daysInMonth[2] = 29
end

local maxDays = daysInMonth[tonumber(month)]
print("这个月的最大天数是:" .. maxDays)

换一种写法

local function getMaxDayOfMonth(year, month)
    local maxDay = 31
    if month == 2 then
        if year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0) then
            maxDay = 29
        else
            maxDay = 28
        end
    elseif month == 4 or month == 6 or month == 9 or month == 11 then
        maxDay = 30
    end
    return maxDay
end
 
local year = 2023
local month = 11
local maxDay = getMaxDayOfMonth(year, month)
print(maxDay)

相关推荐

  1. lua获取某月天数

    2023-12-05 20:30:01       47 阅读
  2. Hostinger怎么购买省钱,面额优惠券获取

    2023-12-05 20:30:01       34 阅读
  3. Springboot获取实时天气

    2023-12-05 20:30:01       39 阅读
  4. PHP获取数组中小值和下标

    2023-12-05 20:30:01       48 阅读
  5. C语言——oj刷题——获取月份天数

    2023-12-05 20:30:01       47 阅读
  6. iOS学习- iOS获取指定月的天数

    2023-12-05 20:30:01       23 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-05 20:30:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-05 20:30:01       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-05 20:30:01       82 阅读
  4. Python语言-面向对象

    2023-12-05 20:30:01       91 阅读

热门阅读

  1. 【Android 线程】在子线程中更新UI

    2023-12-05 20:30:01       56 阅读
  2. spark学习一-------------------Spark算子最详细介绍

    2023-12-05 20:30:01       50 阅读
  3. 再探Docker:从Docker基础到跨服务器部署

    2023-12-05 20:30:01       34 阅读
  4. SSL证书认证对搜索引擎有影响吗?

    2023-12-05 20:30:01       64 阅读
  5. 如何判别使用的junit是4还是5

    2023-12-05 20:30:01       52 阅读
  6. 异常与junit

    2023-12-05 20:30:01       57 阅读
  7. CF 1901B Chip and Ribbon 学习笔记

    2023-12-05 20:30:01       60 阅读
  8. springcloud==ribbon

    2023-12-05 20:30:01       60 阅读
  9. 【光的波长和频率计算】

    2023-12-05 20:30:01       60 阅读
  10. prompt提示

    2023-12-05 20:30:01       47 阅读
  11. Linux C语言 32-网络编程之UDP例程

    2023-12-05 20:30:01       63 阅读