SDL monotonic ticks to local civil time conversion
0 reputation · 07 Oct 2024, 11:56 UTC
0 reputation · 07 Oct 2024, 11:56 UTC
The goal is to convert SDL_GetTicks64 elapsed milliseconds into a regional wall-clock date-time for application logging and scheduled events.
SDL_GetTicks64 is a monotonic counter that starts at SDL initialization and has no relationship to the Unix epoch, an IANA time zone, or daylight saving rules. SDL provides no civil date formatting or time zone database access, so an external operating-system or library call is required. The unresolved decision is how to anchor SDL ticks to a specific wall-clock reference and which time zone source governs the conversion.
Should SDL initialization time be paired with a simultaneous system wall-clock timestamp to establish a stable offset? Which time zone source should take precedence when converting SDL ticks to local civil time? How should daylight saving time transitions be handled when the offset between monotonic ticks and wall-clock time changes?
35275 reputation · 07 Oct 2024, 14:39 UTC
SDL_GetTicks64() to civil time, you must establish a temporal anchor at application initialization. Since SDL ticks are monotonic and unrelated to the Unix epoch, they cannot be converted directly without knowing the specific point where the counter started relative to the system wall-clock.The most reliable method is to capture two values simultaneously when your application starts or initializes SDL. This creates a fixed offset that can be applied to any future tick count to estimate the current time.
SDL_GetTicks64() and a system-specific time function (e.g., time() in C, chrono in C++).Offset = SystemTime - SDLTicks.CurrentTime = Offset + (CurrentTicks - AnchorTicks).Because this method relies on the system wall-clock for the anchor, it is susceptible to changes in the OS environment, such as Daylight Saving Time (DST) transitions or manual user adjustments.
If your application runs for long periods across a DST boundary, the static offset will become inaccurate. To handle this, you should implement a re-synchronization strategy:
n// Initialization
uint64_t anchor_ticks = SDL_GetTicks64();
time_t anchor_time = time(NULL); // System wall epoch
int64_t offset_ms = (int64_t)(anchor_time * 1000) - anchor_ticks;
// Conversion later
uint64_t current_ticks = SDL_GetTicks64();
int64_t current_time_ms = offset_ms + (int64_t)current_ticks;
time_t current_epoch = (time_t)(current_time_ms / 1000);
struct tm *local_tm = localtime(¤t_epoch);
Note: This approach assumes the system clock does not drift significantly between the anchor point and the calculation. If high-precision scheduling is required across NTP updates, consider a library that handles monotonic clocks.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.