day night system roblox code example

Example 1: Day/Night script in roblox studio

-- dayLength defines how long, in minutes, a day in your game is. Feel free to alter it.
local dayLength = 12

local cycleTime = dayLength*60
local minutesInADay = 24*60

local lighting = game:GetService("Lighting")

local startTime = tick() - (lighting:getMinutesAfterMidnight() / minutesInADay)*cycleTime
local endTime = startTime + cycleTime

local timeRatio = minutesInADay / cycleTime

if dayLength == 0 then
	dayLength = 1
end

repeat
	local currentTime = tick()
	
	if currentTime > endTime then
		startTime = endTime
		endTime = startTime + cycleTime
	end
	
	lighting:setMinutesAfterMidnight((currentTime - startTime)*timeRatio)
	wait(1/15)
until false

Example 2: how to make a 24 minute day night script

local StartTime = 12

local showTime = true 

function startDayLoop() 
	local l = game.Lighting 
	l.TimeOfDay = StartTime 
	local t = StartTime 
	local m = nil 
	local am = " AM" 
	local pm = " PM" 
	if (showTime) then 
		local M = Instance.new("Hint") 
		M.Name = "Time" 
		M.Text = "Time - " .. string.sub(l.TimeOfDay,1,2) .. string.sub(l.TimeOfDay,3,5) 
		M.Parent = game.Workspace 
		m = M 
	end 
	while true do 
		l:SetMinutesAfterMidnight(l:GetMinutesAfterMidnight() +0.06) 
		if (showTime) then 
			if (tonumber(string.sub(l.TimeOfDay,1,2))/12 >= 1) then 
				if (tonumber(string.sub(l.TimeOfDay,1,2))/12 == 1) then 
					m.Text = "Time - 12" .. string.sub(l.TimeOfDay,3,5) .. pm 
				else 
					m.Text = "Time - " .. tostring(tonumber(string.sub(l.TimeOfDay,1,2))-12) .. string.sub(l.TimeOfDay,3,5) .. pm 
				end 
			else 
				if (tonumber(string.sub(l.TimeOfDay,1,2)) == 0) then 
					m.Text = "Time - 12" .. string.sub(l.TimeOfDay,3,5) .. am 
				else 
					m.Text = "Time - " .. string.sub(l.TimeOfDay,1,2) .. string.sub(l.TimeOfDay,3,5) .. am 
				end 
			end 
		end 
		wait(0.06) 
	end 
end 

startDayLoop()

-- 24 Minute Day/Night Script By:
-- Rigby#9052 ON Discord.

Tags:

Misc Example