1
votes

I am developing a plugin written in Lua.

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() does not work.

Is there a library or something similar that I can work with?

+Yeah I thought about splitting the string into parts, but I also need a way to add/subtract time

2

2 Answers

2
votes

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.

1
votes

If you need to only compare two time, you don't need to get each time's Unix timestamp. One possible solution is to get the time fields from the string like this:

local time = "1/17/2014 6:50 PM"
local month, day, year, hour, minute, am_pm = time:match("(%d+)/(%d+)/(%d+)%s+(%d+):(%d+)%s+(%w+)")

print(month, day, year, hour, minute, am_pm)

Output: 1 17 2014 6 50 PM

Then compare two time from comparing their year, if they are equal, then month, and so on. Remember to use tonumber to compare them by number, not the string itself.