Round time to 5min interval in Lua

Viewed 102

I have a string variable that I have to round up to 5 min interval but to keep it as string, example: 12:23am should be 12:25am 12:58pm should be 01:00pm 11:59am should be 12:00pm. I have tried this in lua, but it is not good and I am sure there is a better way to to this. Maybe someone can guide me or possibly help. Here is what I have done:

startRoundH=string.sub(var,1,2)
  startRoundM1=string.sub(var,4,4)
  startRoundM2=string.sub(var,5,5)      
  startAMPM=string.lower(string.sub(var,6,7))
  if(tonumber(startRoundM2))<=2 then startRoundM2="0"
  elseif(tonumber(startRoundM2)>2 and tonumber(startRoundM2)<=7) then startRoundM2="5"
  elseif (tonumber(startRoundM2)==8 or tonumber(startRoundM2)==9) then
      startRoundM2="0"
      if(tonumber(startRoundM1)~=5) then startRoundM1=tonumber(startRoundM1)+1 
      else 
          startRoundM1="0"   
          if(tonumber(startRoundH)<9) then startRoundH=tonumber(startRoundH)+1 startRoundH="0"..startRoundH
          elseif(tonumber(startRoundH)==10 or tonumber(startRoundH)==9) then startRoundH=tonumber(startRoundH)+1 
          elseif (tonumber(startRoundH)==11) then 
              startRoundH="12" 
              if(startAMPM=="am") then startAMPM="pm" else startAMPM="am" end
          elseif (tonumber(startRoundH)==12) then startRoundH="01" end
      end       
  end

Thank you!

1 Answers
local function round5min(var)
   local h, m, ampm = var:match"^(%d+):(%d+)(%a+)$"
   local t = (({am=0,pm=12})[ampm:lower()]+h%12)*60+m+2
   t = t-t%5
   m = t%60
   t = (t-m)/60
   h = t%12
   return ("%d:%02d%s"):format((h-1)%12+1, m, ({"am","pm"})[(t-h)/12%2+1])
end

print(round5min("9:23am"))   --> 9:25am
print(round5min("11:56am"))  --> 11:55am
print(round5min("11:57am"))  --> 11:55am
print(round5min("11:58am"))  --> 12:00pm
print(round5min("11:59am"))  --> 12:00pm
print(round5min("11:59pm"))  --> 12:00am
Related