lua 获取指定年月有多少天(包括闰月)

本文深入探讨了Lua中用于获取指定年月天数的函数实现。通过解析代码逻辑,读者将了解如何利用Lua和os模块的功能准确计算一个月有多少天,这对需要进行日期相关计算的开发者尤其有用。
-------------------------------------------------------------------------
-- 获取指定年月有多少天
--------------------------------------------------------------------------
function getDayByYearMonth(_year, _month)
    local _curYear = tonumber(_year)
    local _curMonth = tonumber(_month)
    if not _curYear or _curYear <= 0 or not _curMonth or _curMonth <= 0 then
        return
    end
    local _curDate = {}
    _curDate.year = _curYear
    _curDate.month = _curMonth + 1
    _curDate.day = 0
    local _maxDay = os.date("%d",os.time(_curDate))
    return _maxDay
end

 

Lua中,你可以使用`os.date()`函数结合一些算术操作来获取每个月的第一和每周的第一的零点时间戳。以下是一个简单的例子: 1. 获取每月第一的时间戳: ```lua local function get_first_day_of_month(year, month) local format = "%Y-%m-01" -- 设置日期格式为年月日,月份从0开始计数 local date_str = os.date(format, {year = year, month = month + 1}) -- 加一是因为 Lua 的 month 参数是从1开始的 return os.time(date_str) -- 将字符串转换为时间戳 end -- 示例:获取2023年1月1日的零点时间戳 local first_day_timestamp = get_first_day_of_month(2023, 1) ``` 2. 获取每周第一的时间戳: ```lua local function get_first_day_of_week(year, week_of_year) local start_of_year = os.date("%Y-01-01", {year = year}) -- 每年的第一 local days_since_start = (week_of_year - 1) * 7 -- 因为一周有7,所以需要减去1 local weekday = os.date("%w", start_of_year) -- 获取每周的第一(0代表周日) local timestamp = os.time(start_of_year) + days_since_start * 24*60*60 - weekday * 24*60*60 -- 考虑到周几的差异 return timestamp end -- 示例:获取2023年第一周的第一(假设默认周一为一周的第一) local first_weekday_timestamp = get_first_day_of_week(2023, 1) ``` 注意:上述示例中的`%Y`, `%m`, `%w`等是Lua的日期格式化占位符,`%Y`表示四位数的年份,`%m`表示两位数的月份,`%w`表示一周中的第几
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值