I am looking for a function to convert date in one timezone to another.
It need two parameters,
I recently did this in Typescript :
// fromTimezone example : Europe/Paris, toTimezone example: Europe/London
private calcTime( fromTimezone: string, toTimezone: string, dateFromTimezone: Date ): Date {
const dateToGetOffset = new Date( 2018, 5, 1, 12 );
const fromTimeString = dateToGetOffset.toLocaleTimeString( "en-UK", { timeZone: fromTimezone, hour12: false } );
const toTimeString = dateToGetOffset.toLocaleTimeString( "en-UK", { timeZone: toTimezone, hour12: false } );
const fromTimeHours: number = parseInt( fromTimeString.substr( 0, 2 ), 10 );
const toTimeHours: number = parseInt( toTimeString.substr( 0, 2 ), 10 );
const offset: number = fromTimeHours - toTimeHours;
// convert to msec
// add local time zone offset
// get UTC time in msec
const dateFromTimezoneUTC = Date.UTC( dateFromTimezone.getUTCFullYear(),
dateFromTimezone.getUTCMonth(),
dateFromTimezone.getUTCDate(),
dateFromTimezone.getUTCHours(),
dateFromTimezone.getUTCMinutes(),
dateFromTimezone.getUTCSeconds(),
);
// create new Date object for different city
// using supplied offset
const dateUTC = new Date( dateFromTimezoneUTC + ( 3600000 * offset ) );
// return time as a string
return dateUTC;
}
I Use "en-UK" format because it is a simple one. Could have been "en-US" or whatever works.
If first argument is your locale timezone and seconde is your target timezone it returns a Date object with the correct offset.