Last active
July 2, 2025 14:25
-
-
Save ramsunvtech/e3420e4723b1b30f46c37282d974a108 to your computer and use it in GitHub Desktop.
convertTimeForLocale
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 convertTimeForLocale(timeString, currentTimezone, targetTimezone) { | |
// Check if time starts with ~ | |
if (!timeString.startsWith('~')) { | |
return timeString; // Return as-is if no ~ prefix | |
} | |
// If same timezone, return as-is | |
if (currentTimezone === targetTimezone) { | |
return timeString; | |
} | |
// Extract time (remove ~) | |
const timeOnly = timeString.substring(1); | |
// Parse time | |
const [time, period] = timeOnly.includes('am') || timeOnly.includes('pm') | |
? [timeOnly.replace(/[ap]m/i, '').trim(), timeOnly.match(/[ap]m/i)?.[0]] | |
: [timeOnly, null]; | |
const [hours, minutes] = time.split(/[:.]/); | |
let hour24 = parseInt(hours); | |
// Convert to 24-hour format if needed | |
if (period) { | |
if (period.toLowerCase() === 'pm' && hour24 !== 12) hour24 += 12; | |
if (period.toLowerCase() === 'am' && hour24 === 12) hour24 = 0; | |
} | |
// Create a date object for today with the given time | |
const today = new Date(); | |
const currentTime = new Date(today.getFullYear(), today.getMonth(), today.getDate(), hour24, parseInt(minutes) || 0); | |
// Get time in current timezone as string, then parse in target timezone | |
const timeInCurrent = currentTime.toLocaleString('en-CA', { | |
timeZone: currentTimezone, | |
year: 'numeric', | |
month: '2-digit', | |
day: '2-digit', | |
hour: '2-digit', | |
minute: '2-digit', | |
second: '2-digit', | |
hour12: false | |
}); | |
// Create new date from the current timezone time | |
const sourceDate = new Date(timeInCurrent); | |
// Convert to target timezone | |
const targetTime = sourceDate.toLocaleTimeString('en-US', { | |
timeZone: targetTimezone, | |
hour: 'numeric', | |
minute: '2-digit', | |
hour12: true | |
}); | |
return `~${targetTime}`; | |
} | |
// Usage examples: | |
console.log(convertTimeForLocale('~9:30pm', 'Asia/Singapore', 'Asia/Kolkata')); // Singapore to India | |
console.log(convertTimeForLocale('~7:00pm', 'Asia/Kolkata', 'Asia/Singapore')); // India to Singapore | |
console.log(convertTimeForLocale('~9:30pm', 'Asia/Singapore', 'Asia/Singapore')); // Same timezone | |
console.log(convertTimeForLocale('meet at 5pm', 'Asia/Singapore', 'Asia/Kolkata')); // No ~ prefix |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment