So, I’m using os.difftime() to find how much time until a certain time is reached. I managed to get the minutes and second working, but the hour goes into negatives instead of 23 hours or etc. (Example: if it’s currently 11 AM, and the time reached needs it to be 10 AM, it will do -1 hours instead of 23.)
Here is my script (ServerScript):
local countdownGui = script.Parent
local countdownText = countdownGui:WaitForChild("TextLabel")
while wait(1) do
local time1 = os.date("*t")["hour"]
local time2 = os.date("*t")["sec"]
local time3 = os.date("*t")["min"]
local hour = os.date("%H", 1621953121)
local minute = os.date("%M", 1621951245)
local second = os.date("%S", 1621953239)
local hoursBetween = os.difftime(hour, time1)
local secondsBetween = os.difftime(second, time2)
local minutesBetween = os.difftime(second, time3)
local textString = "Daily Jobs - New Jobs In " .. hoursBetween .. ":".. minutesBetween.. ":" .. secondsBetween
countdownText.Text = textString
if hoursBetween == 0 then
if minutesBetween == 0 then
if secondsBetween == 0 then
print("h")
end
end
end
end
You can solve this by adjusting for negatives. If the value is negative, you just want to add it to 24 and that will give you the correct difference:
if hoursBetween < 0 then
hoursBetween += 24
end
I would recommend instead just subtracting the two times and calculating how many hours, minutes, and seconds it is:
local secondsPerMinute = 60
local secondsPerHour = 60 * secondsPerMinute
local secondsPerDay = 24 * secondsPerHour
-- The two different times
local nowTime = os.clock()
local otherTime = nowTime + secondsPerDay * 2 + secondsPerHour * 3 + secondsPerMinute * 34 + 16 -- Two days, three hours, 34 minutes and 16 seconds from now
-- Calculating the seconds between them
local difference = otherTime - nowTime -- Subtract the two times
local function getTime(timeDiff)
local days = timeDiff / secondsPerDay -- How many days total are in the time
local hours = days%1 * secondsPerDay / secondsPerHour --Get the extra time that isn't a full day (days%1) and turn it back into seconds, then calculate how many hours that is
local minutes = hours%1 * secondsPerHour / secondsPerMinute -- Same thing as above but turning the hours to seconds then back to minutes
local seconds = minutes%1 * secondsPerMinute -- Same thing as above, but, turning the minutes back to seconds
return math.floor(days), math.floor(hours), math.floor(minutes), math.floor(seconds)
end
local days, hours, minutes, seconds = getTime(difference) -- Calculate the hours minutes and seconds
print(days, hours, minutes, seconds) -- 2 3 34 16 (2 days, 3 hours, 34 minutes, 16 seconds)
You can also extend this to weeks (7 * secondsPerDay) and to months (4 * secondsPerWeek) (and if you want, years as 365 * secondsPerDay).
If difference is negative you know it was that long ago, rather than that long in the future. (In that case you can pass math.abs(difference) to getTime if you wanted to account for that)