Us Time Handle
let newDate;
// 1. Determine User's Time Zone (if possible)
if (langCode) {
try {
newDate = moment.utc(date).tz(langCode);
} catch (error) {
console.error("Error converting date to user's time zone:", error);
// Handle the error (e.g., use UTC time or display an error message)
}
} else {
// 2. Handle Unknown Time Zone (improved heuristic)
const offset = moment.utc(date).utcOffset() / 60; // Get UTC offset in hours
// Consider a mapping of offsets to time zones (replace with your data)
const timeZoneMapping = {
'-4': 'US/Eastern', // Eastern Time (DST)
'-7': 'US/Pacific', // Pacific Time (DST)
// Add other time zones as needed
};
const potentialTimeZone = timeZoneMapping[offset.toString()];
if (potentialTimeZone) {
newDate = moment.utc(date).tz(potentialTimeZone);
} else {
// Handle cases where no matching offset is found
console.warn("Unknown user time zone, using UTC:", date);
newDate = moment.utc(date); // Use UTC as a fallback
}
}
// 3. Ensure DST Applied (heuristics)
if (newDate.isBefore(moment.utc().tz(newDate.zoneName()))) {
newDate = newDate.add(1, 'hour'); // Adjust for potential DST if before current time
}
const formattedDate = newDate.format('MMMM Do, YYYY');
console.log("Formatted date:", formattedDate);
Comments
Post a Comment