How to get time till next month

I have a leaderboard script where I wanna basically find out when the next month is, that way I can reward players each end of month.

local DayLength = 60 * 60 * 24
local MonthLength = DayLength * 30

local MonthInt = math.floor(os.time() / MonthLength)

local NextMonthInt = MonthInt + 1
local NextMonthTime = NextMonthInt * MonthLength

The NextMonthTime should be the os.time() of March 1st.

However, when trying to display it on the client, it’s saying that’s 3 days and 20 hours away?

local NextMonthTime = LeaderboardService:GetTimeToNextMonth()

	while true do
		local TimeLeft = NextMonthTime - os.time()
		local TimeLabel = Library:ConvertTime(TimeLeft, 4, true)
		self.Instance.Board.TimeUI.Frame.Time.Text = TimeLabel

		task.wait(1)
	end

However, there’s only 2 days left, so I am unsure where it’s getting this extra time from?

2 Likes

You set it as always 30 days and there is 28 days this month?

we can use the modulus operator

local secondsPerMonth = 2629800
local currentTime = os.time()
local secondsPastThisMonth = currentTime % secondsPerMonth
local secondsRemainingThisMonth = secondsPerMonth - secondsPastThisMonth

you can find out more about how the modulus operator works here

but like StopMo_Gamer said every month is not the same length

so another option is to use

local dayOfTheMonth = tonumber(os.date("%d"))

if dayOfTheMonth == 1 then
	print("Today is the first day of the month lets give everyone there gift")
end

and here is a way we can workout how many seconds are left till the next month

local currentYear = tonumber(os.date("%Y"))
local currentMonth = tonumber(os.date("%m"))
local nextMonthTime = os.time({year=currentYear, month=currentMonth + 1, day=1})
local secondsRemainingThisMonth = nextMonthTime - os.time()
local daysRemainingThisMonth = secondsRemainingThisMonth / 86400
1 Like