Skip to content

Instantly share code, notes, and snippets.

@learyjk
Last active October 3, 2023 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save learyjk/72d3fab91fed51c48e45e5983844ca63 to your computer and use it in GitHub Desktop.
Save learyjk/72d3fab91fed51c48e45e5983844ca63 to your computer and use it in GitHub Desktop.
Converts times on the Webflow Conf website to users' timezone.
function isValidTimeFormat(timeStr) {
const twelveHourFormat = /^(\d{1,2}:\d{2} [AP]M)$/i;
const twentyFourHourFormat = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
if (twelveHourFormat.test(timeStr)) {
return { valid: true, is24HourFormat: false };
} else if (twentyFourHourFormat.test(timeStr)) {
return { valid: true, is24HourFormat: true };
} else {
return { valid: false, is24HourFormat: false };
}
}
/*
* SF (PDT): "-07:00"
* Chicago (CDT): "-05:00"
* New York (EDT): "-04:00"
* London (BST): "+01:00"
*/
function convertToLocal(timeString, offsetFromGMT = '-00:00') {
let hour, minute;
const formatInfo = isValidTimeFormat(timeString);
if (!formatInfo.valid) {
return timeString; // Return the original string if it's not a valid time format.
}
if (formatInfo.is24HourFormat) {
[hour, minute] = timeString.split(':').map(num => parseInt(num, 10));
} else {
let minutePart, meridiem;
[hour, minutePart] = timeString.split(':');
[minute, meridiem] = minutePart.split(' ');
hour = parseInt(hour, 10);
minute = parseInt(minute, 10);
if (meridiem.toUpperCase() === 'PM' && hour !== 12) {
hour += 12;
} else if (meridiem.toUpperCase() === 'AM' && hour === 12) {
hour = 0;
}
}
const isoString = `2022-04-01T${String(hour).padStart(2, '0')}:${minute.toString().padStart(2, '0')}:00.000${offsetFromGMT}`;
const dateObj = new Date(isoString);
// Convert to local time string based on format.
let localTime;
if (formatInfo.is24HourFormat) {
localTime = dateObj.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit', hour12: false });
} else {
localTime = dateObj.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit', hour12: true });
}
return localTime;
}
document.querySelectorAll('h3.eyebrow.u-mb-0').forEach(h3 => {
const timeString = h3.textContent.trim();
if (isValidTimeFormat(timeString).valid) {
/*
* SF (PDT): "-07:00"
* Chicago (CDT): "-05:00"
* New York (EDT): "-04:00"
* London (BST): "+01:00"
*/
const localTime = convertToLocal(timeString, '-07:00'); // Change this parameter.
console.log({ timeString, localTime });
h3.textContent = localTime;
}
});
@learyjk
Copy link
Author

learyjk commented Sep 30, 2023

Hi Matt! 👋
Hi Corey! 🫡

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment