1
votes

Below is an example of a countdown timer for Corona SDK written in LUA. How would I add days, months and years to this?

local function updateTime()
-- decrement the number of seconds
secondsLeft = secondsLeft - 1

-- time is tracked in seconds.  We need to convert it to minutes and seconds
local minutes = math.floor( secondsLeft / 60 )
local seconds = secondsLeft % 60

-- make it a string using string format.  
local timeDisplay = string.format( "%02d:%02d", minutes, seconds )
clockText.text = timeDisplay

end

1

1 Answers

0
votes

Days (and hours) would be trivial, but what about months and years? Since you have no timestamp telling us of how many seconds left to what, it's hard knowing exactly how many months, depending on the length of the months (28, 29, 30 or 31 days). The same with years if we consider leap years as well. In any case, here's something that might be sufficient:

local SECONDS_IN_HOUR = 60 * 60
local SECONDS_IN_DAY = 24 * SECONDS_IN_HOUR
local SECONDS_IN_MONTH = 30 * SECONDS_IN_DAY -- assuming an average of 30 days per month
local SECONDS_IN_YEAR = 365 * SECONDS_IN_DAY

local years = math.floor((secondsLeft / SECONDS_IN_YEAR) % 365)
local months = math.floor((secondsLeft / SECONDS_IN_MONTH) % 12)
local days = math.floor((secondsLeft / SECONDS_IN_DAY) % 30)
local hours = math.floor((secondsLeft / SECONDS_IN_HOUR) % 24)
local minutes = math.floor((secondsLeft / 60) % 60)
local seconds = secondsLeft % 60