日期时间基本使用

时间戳转字符串

function Test1()
    local now = os.time()
    print(os.date("%Y-%m-%d", now)) --2022-01-05
    print(os.date("%y-%m-%d", now)) --22-01-05
    print(os.date("%H:%M:%S", now)) --16:08:00
    print(os.date("%p %I:%M:%S", now)) --PM 04:08:00

    print(os.date("%x", now)) --01/05/22
    print(os.date("%c", now)) --01/05/22 16:08:00

    print(os.date("%b", now)) --Jan
    print(os.date("%B", now)) --January

    print(os.date("%a", now)) --Wed
    print(os.date("%A", now)) --Wednesday
end

 

时间戳转DateTime对象

function Test2()
    local utcSec = os.time() --0时区

    local dateTime1 = os.date("*t", utcSec) --内部会加上时区
    local str1 = string.format("%s-%02d-%02d %02d:%02d:%02d", dateTime1.year, dateTime1.month, dateTime1.day, dateTime1.hour, dateTime1.min, dateTime1.sec)
    print(str1)

    local dateTime2 = os.date("!*t", utcSec) --内部不加时区
    local str2 = string.format("%s-%02d-%02d %02d:%02d:%02d", dateTime2.year, dateTime2.month, dateTime2.day, dateTime2.hour, dateTime2.min, dateTime2.sec)
    print(str2)

    print(dateTime1.isdst) --夏令时
    print(dateTime1.yday) --一年中的第几天
    print(dateTime1.wday) --周几(1表示周日, 2表示周一, 7表示周六)
end

 

DateTime转时间戳

function Test3()
    local dateTime = { year = 1970, month = 1, day = 1, hour = 8, min = 0, sec = 3 }
    local utcSec = os.time(dateTime) --内部减掉时区
    print(utcSec) --3(处在东8区时)
end

 

明天几月几号

function TomorrowDateTime()
    local timestamp = os.time() + 24 * 3600
    local dt = os.date("*t", timestamp)
    return dt.month, dt.day
end

 

posted @ 2022-01-27 23:14  yanghui01  阅读(70)  评论(0编辑  收藏  举报