将unix时间转换为月份数?

时间:2016-02-13 11:56:15

标签: date unix lua unix-timestamp roblox

使用os.time我怎样才能知道自unix时代(Unix时间戳)以来已经过了多少个月

我只需要一个月的身份证,所以任何类型的数字都可以,只要它每个月都有变化,并且可以反转以获得实际月份。

2 个答案:

答案 0 :(得分:2)

local function GetMonth(seconds)
    local dayduration,year = 3600*24
    local days={31,0,31,30,31,30,31,31,30,31,30,31}
    for i=1970,10000 do -- For some reason too lazy to use while
        local yeardays = i%4 == 0 and i%100 ~= 0 and 366 or 365
        local yearduration = dayduration * yeardays
        if yearduration < seconds then
            seconds = seconds - yearduration
        else
            year = i break
        end
    end
    days[2]=(year%4==0) and 29 or 28
    seconds = seconds%(365*24*3600)
    for i=1,12 do
        if seconds>days[i]*dayduration then
            seconds=seconds-days[i]*dayduration
        else
            return --i + year*12  <-- If you want a unique ID
        end
    end
end

目前,它将给出2号,因为它是2月份。如果您在最后取消注释唯一ID的代码,您将获得554,这意味着我们目前处于自纪元以来的第554个月。

正如Jean-BaptisteYunès在答案的评论中所说,我不确定你的判决是否存在:

  

注意:这适用于Lua,但我无法使用os.date

意味着你没有os.date,或者你不知道如何使用它。你有两个案例的答案,你可以使用你需要的那个。

答案 1 :(得分:-1)

这可以解决问题:

print (os.date("*t",os.time())["month"])

os.time()为您提供当前日期作为数字。 os.date("*t",...)将其转换为一个表格,其中month等于与该日期对应的月份数。