# Help making code more efficient

Hello.

I spent a an hour or two working on this function that converts a high amount of seconds (i.e. 2,000,000) to, depending on how many seconds it is, minutes, hours, days, months, and/or years.

Here is what I have as of now:

``````function module.SortSeconds(total)
-- vals
local values = {}

values = {"Year",0}
local years = values
values = {"Month",0}
local months = values
values = {"Week",0}
local weeks = values
values = {"Day",0}
local days = values
values = {"Hour",0}
local hours = values
values = {"Minute",0}
local minutes = values
values = {"Second",0}
local seconds = values

seconds = total

if total > 157680000 then -- I added this because it kept crashing with higher amounts of seconds.
seconds = 0
years = 5
end

-- the stuffs
while true do
if seconds >= 60 then
minutes += 1
seconds -= 60
elseif minutes >= 60 then
hours += 1
minutes -= 60
elseif hours >= 24 then
days += 1
hours -= 24
elseif days >= 31 then
months += 1
days -= 31
elseif months >= 12 then
years += 1
months -= 12
else
break
end
end
return values
end
``````

Any help is appreciated.

Thanks,
Ham

You’d be better off moving this to the Code Review section for help with this.

Sorry, I don’t use the devforum often.

Thats ok, dont give me the solution, just change its category.

I also clicked scripting support. No idea why it went here lol.

You can still change it. . . .

Oh, I already did that. Thanks for the suggestion though.

1 Like

Your function works but it’s very inefficient.
I wouldn’t use a loop for such things; here’s how I do it.

``````function GetDate:Remaining(st)
if st > 0 then
local t = math.floor(st)
local m = math.floor(t / 2629743.83)
t = t - m * 2629743.83
local w = math.floor(t / 604800)
t = t - w * 604800
local d = math.floor(t / 86400)
t = t - d * 86400
local h = math.floor(t / 3600)
t = t - h * 3600
local mi = math.floor(t / 60)
t = t - mi * 60
local date = {
m = m,
w = w,
d = d,
h = h,
mi = mi,
se = math.floor(t)
}
return date
end
return "Expired"
end
``````

Calling this function with a positive value of seconds will return a table with it’s values.

``````local info = GetDate:Remaining(60) --60 seconds
print(info)
``````

Kinda just looks like you copied it from else where…Nevertheless, thanks. I’ll tweak it to work for my situation.

If you don’t want help don’t ask 3 Likes

wow i felt that into my soul right now xD