简体   繁体   中英

How to add timezone offset to string without changing the time?

I have a time string like this 2021-12-29T01:30:00.105Z . I want to add offset for a timezone without changing the date and time. So it should look like this after conversion - 2021-12-29T01:30:00+08:00 for "Asia/Kuala_Lumpur" timezone.

So 2021-12-29T01:30:00.105Z -> 2021-12-29T01:30:00+08:00

I cannot do a string replace since the timezone will be dynamic and does not always has to be "Asia/Kuala_Lumpur".

I am using moment and moment-timezone libraries and have tried different ways to get the required result but none seems to work.

Please help.

If you have the IANA name for the timezone and you want to change the timezone of a date in +XX:XX format without modifying the time, you can calculate the offset and replace it in the string:

 const timeString = '2021-12-29T01:30:00.105Z'; const timezone = 'Asia/Kuala_Lumpur'; const offset = Intl.DateTimeFormat([], {timeZone: timezone, timeZoneName: 'longOffset'}).formatToParts().find(o => o.type === 'timeZoneName').value.match(/\+.*$/)[0]; const newTimeString = timeString.replace(/\..+Z$/, offset); console.log(timeString); console.log(newTimeString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM