I need solution to Convert timestamp from one country time zone to another country time zone irrespective of local time zone. I am looking for some help.
Consider that My local time zone is Canada(GMT-5). 11:32 am Tuesday, 6 December 2022 (GMT-5) I do have date and time in string format from Alaska time zone AK, USA (GMT-9) 7:32 am Tuesday, 6 December 2022 (GMT-9) to Germany time zone 5:32 pm Tuesday, 6 December 2022 (GMT 1). Logic should return me 5:32 pm Tuesday, 6 December 2022
function should take 3 arguments like date in string format, from time zone, to time zone. And it should return a date and time in to time zone format
Function convertTimeZone(date, fromTimeZone, toTimeZone){ }
CodePudding user response:
You can use the moment.tz constructor
to parse your input timestamp.
The resulting date can then be converted to the output timezone using the .tz()
method.
We'd then use the .format()
method to output the desired timestamp.
function convertTimeZone(date, fromTimeZone, toTimeZone, outputFormat = 'YYYY-MM-DD hh:mm a') {
const from = moment.tz(date, fromTimeZone);
return from.tz(toTimeZone).format(outputFormat);
}
const date = '2022-12-06 11:32';
const fromTimeZone = 'Canada/Eastern';
const timeZones = [fromTimeZone, 'UTC', 'US/Alaska', 'Europe/Berlin'];
console.log('Timezone'.padEnd(22), 'Time');
for(let toTimeZone of timeZones) {
console.log(`${toTimeZone}`.padEnd(22), convertTimeZone(date, fromTimeZone, toTimeZone));
}
.as-console-wrapper { max-height: 100% !important; }
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>
CodePudding user response:
take the time from the timezone and convert it to another timezone. Moment works like this as chaining it.
moment.tz('2022-01-01T12:00:00.000Z', fromTz).tz(toTz)