I am trying to reset a ISO time to local time, but I am having some trouble converting it.
Currently, I:
// incoming ISO date
let date = new Date('2021-11-08T20:31:23.746Z');
// 1. get timezone offset in hours
const offset = date.getTimezoneOffset() / 60;
// 2. calculate local hour
let localHour = date.toISOString().split('T')[1].substring(0, 2) - offset;
// 3. calculate local time
let localTime = date.toISOString().replace(/[T-:]/, localHour);
console.log(localTime);
// ISO Date
// 2021-11-08T20:31:23.746Z (original)
// 2021-11-08T13:23.746Z (local timezone)
In step 3, I am trying to only replace the first two characters after 'T', however, this is not the correct solution with Regex.
The Date constructor automatically converts the date to your locale after parsing.
// incoming ISO date
let date = new Date('2021-11-08T20:31:23.746Z');
const res = date.toLocaleString().replaceAll('/', '-').split(', ').join('T')
console.log(res)
// ISO Date
// 2021-11-08T20:31:23.746Z (original)
// 2021-11-08T13:23.746Z (local timezone)