← Pixel Dreamer Studio

Turn a time of day in hours into clock text that is always right

Round the time to the nearest second, then split it into hours and minutes with whole numbers.

A day-night cycle usually keeps the time as hours, like 7.5 for half past seven. int((hours - int(hours)) * 60) looks right, but 1/60 is not exact in a float, so 1:01 comes out as 0.99999 of a minute and shows 1:00. In our Godot 4.7 test that happened for 623 of the 1,440 minutes of a day. roundi() instead shows 7:60 for the last half minute of every hour. Round to whole seconds first: every minute right, never :60.

The code

Set your clock Label's text to clock_text(time_of_day), where the time of day is in hours from 0 to 24, the same number that drives the sun. Times past 24 wrap around to the next day.

extends Node
## Clock text for an in-game time of day kept in hours (0 to 24), as a day-night cycle uses.
## Never shows 7:60, and never skips or repeats a minute.


static func clock_text(hours: float) -> String:
	var secs := roundi(fposmod(hours, 24.0) * 3600.0)  # round to the nearest second first
	var mins := (secs / 60) % (24 * 60)
	return "%02d:%02d" % [mins / 60, mins % 60]

What we measured

Every minute of the day as hours = minute / 60, and a running day at 60 fps where 1 real second is 1 game minute (86,400 frames). Two runs with the same numbers.

Why it happens

A float stores 1/60 as a number very slightly off. Multiply it back by 60 and you can land on 0.9999999 instead of 1, and int() turns that into 0. roundi() fixes that, but it also rounds 59.6 minutes up to 60 without moving the hour. Rounding the whole time to seconds first takes away the tiny error, and then whole-number division and % give hours and minutes that always add up.

What to change

The sky and sun for that time: day-night cycle with sun and sky. Effects only at night, even across midnight: night-only effects. Sleeping until morning without the clock running backwards: a time skip past midnight.

Ready-made skies: PD Toon Skies has 40 painted skies and a live sky shader with a 0 to 24 time of day slider.

Tested in Godot 4.7 with the Compatibility renderer.

Ready-made: PD Toon Skies has 40 painted skies and a live sky shader with a 0 to 24 time of day slider.

More how-tos: Skies and backgrounds