ChioyFy
ChioyFy

Reputation: 11

Lua Date Difference

I want to know if you can get the date difference of two dates that are predefined or dynamic in a long run.

Do you need a proper date format when using this function?

function datediff(d1, d2, ...)

    col_date1 = os.time({year = d1:year(), month = d1:month(), day = d1:day() , hour = d1:hour(), min = d1:minute(), sec = d1:second() })
    col_date2 = os.time({year = d2:year(), month = d2:month(), day = d2:day() , hour = d2:hour(), min = d2:minute(), sec = d2:second() })

    local arg={...}
    if arg[1] ~= nil then
        if arg[1] == "min" then
            return math.abs((col_date1 - col_date2) / 60)
        elseif arg[1] == "hour" then
            return math.abs((col_date1 - col_date2) / 3600)
        elseif arg[1] == "day" then
            return math.abs((col_date1 - col_date2) / 86400)
        end
    end
    return math.abs(col_date1 - col_date2)
    --return 0
end

This is the code. But I have no idea how this work exactly. The input should be like 31122017 - 31122016 is 1 year. or something like that.

Upvotes: 1

Views: 2479

Answers (1)

Jack Taylor
Jack Taylor

Reputation: 6217

This code takes custom date objects as input. So, for example, if you had a date object d that represented a date like 2017-05-22, then calling d:year() would give you the number 2017, d:hour() would give you the number 5, etc.

There are no functions to make objects like this in standard Lua, so the project this code is in must be using a separate date library. You need to find out how to create the date objects that your project expects, and then pass those into the function.

Upvotes: 1

Related Questions