JavaScript Date Utility Function
/**
* Converts UTC datetime to user's current local time string.
* @param {string|Date} utcInput - UTC datetime string or Date object.
* @param {Object} [options] - Intl.DateTimeFormat options override.
* @param {boolean} [includeZone=false] - Whether to append time zone name.
* @returns {string} Localized string.
*/
function formatLocalTime(utcInput, options = {}, includeZone = false) {
const utcDate = utcInput instanceof Date ? utcInput : new Date(utcInput);
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const formatter = new Intl.DateTimeFormat([], { timeZone, ...options });
const formatted = formatter.format(utcDate);
return includeZone ? `${formatted} (${timeZone})` : formatted;
}
Example usage:
formatLocalTime("2025-10-09T06:45:00Z");
// Default medium date + short time
formatLocalTime("2025-10-09T06:45:00Z", { dateStyle: "long" });
// Long date only
formatLocalTime("2025-10-09T06:45:00Z", { timeStyle: "short" });
// Time only
formatLocalTime("2025-10-09T06:45:00Z", { hour: "2-digit", minute: "2-digit" }, false);
// Custom format, no zone