Search code examples
datetimelua

Convert date to Unix time without os.time()


I am developing a plugin written in Lua, and I need a way to calculate Unix time or at least a way to compare 2 date strings.

The function I can use only returns date string in the following format

"1/17/2014 6:50 PM"

Is there a way to convert this string to a Unix time?

Unfortunately I don't have access to the OS library so things like os.time() do not work.

Is there any library or something similar that I can work with? I also thought about splitting the string into parts, but I need a way to add/subtract time


Solution

  • Just compare normalized timestamps:

    function normalize(a)
        local m,d,y,h,mi,n=a:match("(%d+)/(%d+)/(%d+)%s+(%d+):(%d+)%s+(%w+)")
        if n=="PM" then h=h+12 end
        return string.format("%04d%02d%02d%02d%02d",y,m,d,h,mi)
    end
    

    Date arithmetic is another story. For a complete, pure Lua date library, see luatz or https://github.com/Tieske/date.