Lua应用示例
【Lua示例】读取LM2-Q系列激光位移传感器的测量值
【Lua示例】按照日期动态创建目录并保存输入的图片
【Lua示例】单字节字符串拆分归类
【Lua示例】ASCII码转换
【Lua示例】获取指定月份天数
本站点使用 MrDoc 构建
-
+
【Lua示例】获取指定月份天数
## 概述 根据传入的年份和月份,计算该月共有多少天。自动处理闰年2月的情况,无需手动判断闰年规则。适用于生产排程、月度统计、日历计算等需要按月统计的场景。 --- ## 技术说明 - **环境**:NASI 单字节,VG3 Lua Runtime - **依赖**:`LuaSystem`(GetYear / GetMonth)、`LuaLog`(Debug) - **排序**:无 - **边界**:利用 `os.time` 的自动日期归一化特性——`day=0` 取上月最后一天,`month=13` 自动推到下一年1月,因此跨年计算(如2025年13月)也能正确返回结果 --- ## 函数列表 ### 1. `GetDaysInMonth(year, month)` 根据年份和月份返回该月的总天数 ``` 参数: year (number) 年份,如 2026 month (number) 月份,1~12 返回: days (number) 该月天数,如 28、30、31 ``` **示例:** ```lua local days = GetDaysInMonth(2024, 2) -- days = 29(2024年是闰年) ``` --- ## 运行实例 输入:当前日期为 2026年5月 ``` 2026年5月共有 31 天 2024年2月: 29 天 2025年2月: 28 天 ``` --- ## 月份天数参考 | 月份 | 天数 | 说明 | | --- | ----- | ----- | | 1月 | 31 | | | 2月 | 28/29 | 闰年29天 | | 3月 | 31 | | | 4月 | 30 | | | 5月 | 31 | | | 6月 | 30 | | | 7月 | 31 | | | 8月 | 31 | | | 9月 | 30 | | | 10月 | 31 | | | 11月 | 30 | | | 12月 | 31 | | --- ### 场景一:月度生产统计 ```lua -- 统计当月剩余可生产天数 local year = LuaSystem:GetYear() local month = LuaSystem:GetMonth() local day = LuaSystem:GetDay() local totalDays = GetDaysInMonth(year, month) local remainDays = totalDays - day LuaLog:Debug(string.format("本月共 %d 天,已过 %d 天,剩余 %d 天", totalDays, day, remainDays)) ``` ### 场景二:计算指定月的起止时间戳 ```lua -- 获取某月第一天和最后一天的时间戳 local year = 2026 local month = 5 local firstDayTs = os.time({year = year, month = month, day = 1, hour = 0, min = 0, sec = 0}) local lastDay = GetDaysInMonth(year, month) local lastDayTs = os.time({year = year, month = month, day = lastDay, hour = 23, min = 59, sec = 59}) LuaLog:Debug(string.format("%d年%d月: 第一天时间戳=%d, 最后一天时间戳=%d", year, month, firstDayTs, lastDayTs)) ``` --- ## 完整代码 ```lua --============================================ -- 获取指定月份的天数 --============================================ local function GetDaysInMonth(year, month) -- 原理:该月最后一天 = 下个月第0天 local t = os.time({year = year, month = month + 1, day = 0}) return tonumber(os.date("%d", t)) end -- 示例:取当前月份天数 local year = LuaSystem:GetYear() local month = LuaSystem:GetMonth() local days = GetDaysInMonth(year, month) LuaLog:Debug(string.format("%d年%d月共有 %d 天", year, month, days)) -- 示例:取2024年2月(闰年) LuaLog:Debug(string.format("2024年2月: %d 天", GetDaysInMonth(2024, 2))) -- 29 LuaLog:Debug(string.format("2025年2月: %d 天", GetDaysInMonth(2025, 2))) -- 28 ``` *VG3 Lua API · 获取指定月份天数*
李玉军
2026年5月28日 18:50
转发文档
收藏文档
上一篇
下一篇
手机扫码
复制链接
手机扫一扫转发分享
复制链接
Markdown文件
PDF文档(打印)
分享
链接
类型
密码
更新密码