I am trying to reset a ISO time to local time, but I am having some trouble converting it.
Currently, I:
// incomming 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.
CodePudding user response:
The Date constructor automatically converts the date to your locale after parsing.
// incomming 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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Stop right there and don't do this. Date management is hard. You are going to shoot yourself in the foot. Use a library, for example dayjs.
dayjs(date).local().toDate()