Last active
October 3, 2023 16:06
-
-
Save learyjk/72d3fab91fed51c48e45e5983844ca63 to your computer and use it in GitHub Desktop.
Converts times on the Webflow Conf website to users' timezone.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Matt! 👋
Hi Corey! 🫡