日期时间加减

#

--昨天
local dt = { year=2022, month=3, day=1 }
local utcSec = os.time(dt)
utcSec = utcSec - 24 * 3600
local dt2 = os.date("*t", utcSec)

print("yestoday", dt2.year, dt2.month, dt2.day)

 

--明天
local dt = { year=2022, month=2, day=28 }
local utcSec = os.time(dt)
utcSec = utcSec + 24 * 3600
local dt2 = os.date("*t", utcSec)

print("tomorow", dt2.year, dt2.month, dt2.day)

 

---日期加减后, 将日期修正为正确的值
function RefreshDateTime(dt)
    local utcSec = os.time(dt)
    return os.date("*t", utcSec)
end

 

---西方国家一周中的第1天为周日, 我们这边的习惯是周一
function FixWday(dt)
    if 1 == dt.wday then
        dt.wday = 7
    else
        dt.wday = dt.wday - 1
    end
    return dt
end

 

--上个月
local dt = { year=2022, month=1, day=31}
dt.month = dt.month - 1
dt = RefreshDateTime(dt)

print("last month", dt.year, dt.month, dt.day) --2021 12 31

 

--下个月
local dt = { year=2021, month=12, day=31}
dt.month = dt.month + 1
dt = RefreshDateTime(dt)

print("next month", dt.year, dt.month, dt.day) --2022 1 31

 

--下下个月
local dt = { year=2021, month=12, day=31}
dt.month = dt.month + 2
dt = RefreshDateTime(dt)

print("next next month", dt.year, dt.month, dt.day) --2022 3 3

 

--下周一是几月几号
local dt1 = {year=2022, month=6, day=19}
local utcSec = os.time(dt1)
local dt = os.date("*t", utcSec)
FixWday(dt)
local leftDay = 8 - dt.wday --距离周一天数
dt.day = dt.day + leftDay
dt = RefreshDateTime(dt)
print("next monday", dt.year, dt.month, dt.day) --2022 6 20

 

--下个月1号,是周几
local dt = {year=2022, month=6, day=19}
dt.month = dt.month + 1
dt.day = 1
dt = RefreshDateTime(dt)
FixWday(dt)
print(dt.wday) --5

 

posted @ 2022-06-24 23:13  yanghui01  阅读(152)  评论(0编辑  收藏  举报