0

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

user12763413
  • 1,177
  • 3
  • 18
  • 53
  • 2
    Does this answer your question? [Convert UTC date time to local date time](https://stackoverflow.com/questions/6525538/convert-utc-date-time-to-local-date-time) – Idrizi.A Feb 03 '23 at 16:26
  • In your case, since you're using a date in [ISO 8601](https://tc39.es/ecma262/#sec-date-time-string-format) just delete the `Z` from the end of the string for it to not be in UTC when parsed – kikon Feb 03 '23 at 16:32
  • @Enve I tried that already. 2023-02-01T17:00:22.127Z shows as Wed Feb 01 2023 17:00:00 GMT+0530 (India Standard Time). Instead, I want it to be like 2023-02-01 22:30 – user12763413 Feb 03 '23 at 17:11
  • 1
    Check out [Date.prototype.toLocaleString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString). If that's not exactly what you want, Date has other functions like `getDate`, `getMonth`... see https://stackoverflow.com/a/23593099/1354378 – Idrizi.A Feb 03 '23 at 17:25

1 Answers1

1

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"
}
Peter Thoeny
  • 7,379
  • 1
  • 10
  • 20