p5.js Date object and millis() synchronization across regional time zones
0 reputation · 31 Oct 2023, 09:18 UTC
0 reputation · 31 Oct 2023, 09:18 UTC
p5.js utilizes the JavaScript Date object for absolute time tracking and the millis() function for elapsed time since the sketch began. While millis() provides a consistent internal clock independent of the system's regional settings, the Date object is subject to the host environment's local time zone.
When developing time-dependent animations or data visualizations that rely on both absolute timestamps and relative elapsed time, there is a discrepancy in how these two values behave during system clock adjustments, such as Daylight Saving Time (DST) shifts or NTP synchronizations.
What is the recommended approach for maintaining synchronization between the relative millis() counter and localized Date objects to ensure consistent behavior across different global regions?
Date outputs to a specific time zone without external libraries?33275 reputation · 31 Oct 2023, 20:18 UTC
Use a single offset between Date.now() and millis() to translate the sketch’s internal clock into a UTC timestamp, then format that timestamp in the desired zone with Intl.DateTimeFormat. Re‑calculate the offset periodically to absorb system clock drift, DST jumps, or NTP resynchronisation.
millis() is derived from performance.now(), which is monotonic and unaffected by local time zone changes.Date.now() reflects the host’s wall‑clock, including DST and NTP adjustments.millis() to UTC.let startTime = Date.now();let startMillis = millis();let utcOffset = startTime - startMillis;
let utcMs = millis() + utcOffset;
Date from that UTC value:
let utcDate = new Date(utcMs);
Europe/Paris with your zone):
let formatter = new Intl.DateTimeFormat('en-US', {
timeZone: 'Europe/Paris',
hour: '2-digit', minute: '2-digit', second: '2-digit'
});
let formatted = formatter.format(utcDate);
utcOffset:
function refreshOffset() {
let nowTime = Date.now();
let nowMillis = millis();
utcOffset = nowTime - nowMillis;
}
setInterval(refreshOffset, 60000); // every minute
Most modern browsers support Intl.DateTimeFormat with the timeZone option. If you must support older engines, fall back to UTC getters:
function toZone(date, offsetHours) {
let utc = date.getTime();
let zoneTime = new Date(utc + offsetHours*3600*1000);
return zoneTime.toLocaleString();
}
Does the target browser implement Intl.DateTimeFormat with the timeZone option? If not, you’ll need the UTC‑getter fallback above.
utcOffset every minute; it should stay within a few milliseconds unless the system clock changes.performance.now() and Intl.DateTimeFormat (most recent releases).By anchoring millis() to UTC with a recalibrated offset and formatting with Intl.DateTimeFormat, you achieve consistent, zone‑aware timestamps that stay in sync across all global regions without external libraries.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.