Live countdown in player's local time

I would like to have a live countdown to Christmas displayed on a GUI, in each player’s local time. The function I have running currently to find this is as follows:

local christmas = os.time({year = 2021, month = 12, day = 24, hour = 24, min = 0, sec = 0})

local function updateCountdown()
	local localTime = os.time(os.date("*t"))
	local difference = christmas - localTime

	local secondsUntil = os.difftime(christmas,os.time())
	local data = os.date("*t",secondsUntil)
	
	countdown.Text = string.format("%i days, %i hours, %i minutes and %i seconds until Christmas!",data.day,data.hour,data.min,data.sec)
end

-- I also have a loop running this function every second.

I am running into two problems:

  • The time displayed in the game versus the time displayed on a website counting down to Christmas is one day out. This can be fixed by reducing the “day” in the christmas variable to 23, but I’m unsure as to why it’s actually happening in the first place.

  • The time until the event does not display in the player’s local time. For me, it is shown in my local time, however, when I ask a person in a timezone 5 hours behind me to test, the time difference shows. My timezone is GMT.

I am particularly interested in solving problem #2, as I would like the countdown to display the correct amount of time until the date based on the player’s local time. Also, if there are better ways of programming this, I will take this on board.

Thanks. :slightly_smiling_face:

2 Likes

This is because Greenwhich Mean Time has an offset of 0 from Coordinated Universal Time. I’m guessing you are doing this using a Script | Roblox Creator Documentation, which would be running on the server. Regardless of their local time, Roblox servers return UTC time. This is so that events and other things can be synchronized between servers

I only changed your code a bit.

local christmas = os.time({year = 2021, month = 12, day = 25, hour = 0, min = 0, sec = 0})
local countdownString = "%j days, %I hours, %M minutes, and %S seconds until Christmas!"

local function updateCountdown()
	countdown.Text = os.date(countdownString, os.difftime(christmas, os.time()))
end

Note that this should be running in a LocalScript | Roblox Creator Documentation. Other than that is should be running correctly.

However, you’ll notice that the string returned will have the numeric values set in a timeframe. For example, 26 days will read as “026 days”. If you wish to get rid of the 0
s in front of the numbers you can use this function instead:

local function updateCountdown()
	countdown.Text = os.date(countdownString, os.difftime(christmas, os.time())):gsub("%d+", function(x) return tonumber(x) end)
end

It replaces all numeric captures with the number returned through the tonumber function.

1 Like