I would definitely suggest using a specialized date/time library for this purpose.
Timezone conversion in vanilla JavaScript is tricky to say the least (especially converting from a timezone to UTC)
However this is quite straightforward in luxon
:
I'm using the DateTime.fromSQL()
function here since it matches the input timestamp format.
const { DateTime } = luxon;
function convertToUTC(date, tzString) {
const dt = DateTime.fromSQL(date, { zone: tzString });
return dt.setZone('UTC');
}
console.log(convertToUTC("2022-07-12 09:00:00", "America/Chicago"));
console.log(convertToUTC("2022-07-12 09:00:00", "America/Los_Angeles"));
console.log(convertToUTC("2022-07-12 09:00:00", "Europe/London"));
console.log(convertToUTC("2022-07-12 09:00:00", "Etc/GMT+12"));
console.log(convertToUTC("2022-07-12 09:00:00", "Pacific/Kiritimati"));
.as-console-wrapper { max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js" integrity="sha512-Nw0Abk+Ywwk5FzYTxtB70/xJRiCI0S2ORbXI3VBlFpKJ44LM6cW2WxIIolyKEOxOuMI90GIfXdlZRJepu7cczA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
We can do this in vanilla JavaScript, it's just a little awkward.
We're essentially searching for the UTC date that will, when converted to the target timezone, equal the target date.
I'm using the 'sv' language (BCP47 language tag) since it will give us ISO timestamps.
function convertToUTC(date, tzString) {
const dt = Date.parse(toIso(date) + 'Z');
// Go from UTC offset +15 hours to UTC offset -15 hours. This should cover existing / future zones.
for(let offsetMinutes = -900; offsetMinutes <= 900; offsetMinutes += 15) {
const utc = new Date(dt + offsetMinutes * 60000);
if (toIso(date) === toIso(utc, tzString)) {
return toIso(utc, 'UTC') + 'Z';
}
}
}
function toIso(date, timeZone) {
return new Date(date).toLocaleString('sv', { timeZone }).replace(' ', 'T');
}
console.log(convertToUTC("2022-07-12 09:00:00", "America/Chicago"));
console.log(convertToUTC("2022-07-12 09:00:00", "America/Los_Angeles"));
console.log(convertToUTC("2022-07-12 09:00:00", "Europe/London"));
console.log(convertToUTC("2022-07-12 09:00:00", "Etc/GMT+12"));
console.log(convertToUTC("2022-07-12 09:00:00", "Pacific/Kiritimati"));
.as-console-wrapper { max-height: 100% !important; }