NeilJiang
NeilJiang

Reputation: 223

how to compare time in human format in lua?

Is there a way to convert human readable time "09:41:43" to some comparable format?

What I want is function timeGreater(time1, time2), satisfied the below assertion

assert(true == timeGreater("09:41:43", "09:00:42"))
assert(false == timeGreater("12:55:43", "19:00:43")))

Upvotes: 1

Views: 3150

Answers (2)

NickSlash
NickSlash

Reputation: 5075

Converting your time to seconds should work. The code below might work, LUA isn't my strong suit!

function stime(s)
    local pattern = "(%d+):(%d+):(%d+)"
    local hours, minutes, seconds = string.match(s, pattern)
    return (hours*3600)+(minutes*60)+seconds
end

function timeGreater(a, b)
    return stime(a) > stime(b)
end

Upvotes: 4

Paul Kulchenko
Paul Kulchenko

Reputation: 26774

It seems like a simple string comparison may be sufficient (assuming time is valid):

function timeGreater(a, b) return a > b end

assert(true == timeGreater("09:41:43", "09:00:42"))
assert(false == timeGreater("12:55:43", "19:00:43"))

Upvotes: 5

Related Questions