How to convert CST to users time zone Javascript?

Viewed 29

I have this table of times here and I want to convert these CST Times to the users time zone. I also want to change the table header based on the users time zone while matching the header format in the below image.

enter image description here

1 Answers

You can have the time zone offset in minutes using the following. For me, it returns -120. For the header text, a simple function like this could do the job:

function getHeaderText() {
  const yourTimezone = new Date().getTimezoneOffset();
  const plusMinus = yourTimezone >= 0 ? "+" : "-";
  const utcOffset = plusMinus + Math.abs(yourTimezone / 60);
  const timezoneName = Intl.DateTimeFormat().resolvedOptions().timeZone;
  return `Your time zone is set to UTC${utcOffset} (${timezoneName}).`;
}

console.log(getHeaderText());

If you want to play with time I also recommend you to check out JsJoda: https://js-joda.github.io/js-joda/

Related