Hey guys! I’ve recently been redoing some parts of a ban module I made and realized that the method I used for formatting time wasn’t very convenient or clean, so I made a new one.
Special thanks to Wiktor Stribiżew for his post on extracting numbers from strings.
local DURATION_TOKENS = {
{ "year", "y", 31536000 },
{ "month", "mo", 2592000 },
{ "week", "w", 604800 },
{ "day", "d", 86400 },
{ "hour", "h", 3600 },
{ "minute", "m", 60 },
{ "second", "s", 1 },
}
local format: string = '(%f[%d]%d[,.%d]*%f[%D])'
function formatTime(input)
local tokensFound = {}
local totalDurationSeconds: number = 0
if typeof(input) == "number" then
for _, tokenInfo in pairs(DURATION_TOKENS) do
local num: number = math.floor(input/tokenInfo[3]) or 0
if num > 0 then
table.insert(tokensFound, tostring(num.." "..tokenInfo[1]..(num > 1 and "s" or "")))
input = input - (num * tokenInfo[3])
end
end
local outputStr = table.concat(tokensFound, ", ")
return outputStr
elseif typeof(input) == "string" then
for _, tokenInfo in pairs(DURATION_TOKENS) do
local numFound: string? = string.match(input, format .. tokenInfo[2])
if numFound then
local num = tonumber(numFound) or 0
if num > 0 then
table.insert(tokensFound, tostring(num.." "..tokenInfo[1]..(num > 1 and "s" or "")))
end
totalDurationSeconds = totalDurationSeconds + (num * tokenInfo[3])
end
end
local outputStr = table.concat(tokensFound, ", ")
return totalDurationSeconds, outputStr
end
end
I’m sure there are better ways to do this, especially with adding the “s” onto plural numbers, but this worked for me so I’m sharing it with you guys.
If anyone comes up with a better version, feel free to share it in the comments! Thanks!