Home > Net >  Convert UTC to current timezone in javascript
Convert UTC to current timezone in javascript

Time:02-04

I have time as 2023-02-01T17:00:22.127Z which is in UTC. I want to convert this to the timezone of the user from where user is logged in. How can I do this using javascript?

I was trying to use https://yarnpkg.com/package/jstz but couldn’t use a way to convert the time. Please help resolve this issue

CodePudding user response:

Here is a function that converts a UTC date string to a local browser date string with format YYYY-MM-DD hh:MM:

function getLocalDateString(utcStr) {
  const date = new Date(utcStr);
  return date.getFullYear()
      '-'   String(date.getMonth()   1).padStart(2, '0')
      '-'   String(date.getDate()).padStart(2, '0')
      ' '   String(date.getHours()).padStart(2, '0')
      ':'   String(date.getMinutes()).padStart(2, '0');
}

console.log({
  '2023-02-01T00:55:22.127Z': getLocalDateString('2023-02-01T00:55:22.127Z'),
  '2023-02-01T17:00:22.127Z': getLocalDateString('2023-02-01T17:00:22.127Z')
});

Ouput in my timezone:

{
  "2023-02-01T00:55:22.127Z": "2023-01-31 16:55",
  "2023-02-01T17:00:22.127Z": "2023-02-01 09:00"
}
  • Related