-2

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.

doctorsherlock
  • 1,334
  • 4
  • 19
  • 41
  • 1
    Show us what you have tried. Otherwise people are likely to give you the same thing again. You do realize that those strings do not represent same time since first is UTC? – charlietfl Dec 28 '21 at 18:40
  • @charlietfl Yes, I am aware they will represent different time, thanks. – doctorsherlock Dec 28 '21 at 18:45
  • Suggest you be a lot more specific about your use case and the higher level problem you are trying to solve – charlietfl Dec 28 '21 at 18:46
  • Don't understand what you mean by 'timezone will be dynamic' either, need to elaborate on that – skara9 Dec 28 '21 at 18:51
  • @skara9 for a record in a database i have a time like `2021-12-29T01:30:00.105Z` and a timezone like `Asia/Kuala_Lumpur`. But the timezone could be different for different records so I cannot do a string replace with `+08:00` – doctorsherlock Dec 28 '21 at 18:56
  • https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/: "*On passing a second parameter as `true`, only the timezone (and offset) is updated, keeping the local time same.*" – Bergi Dec 28 '21 at 19:22

1 Answers1

0

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);
skara9
  • 4,042
  • 1
  • 6
  • 21