-6

In javascript, one is given:

  1. UTC milliseconds since 1970
  2. timezoneOffset of the local timezone

From the above, how to extract the local time and year implied by the timezoneOffset?

1 Answer 1

1

your question is quite ambiguous, but...

Extracting the exact local time from just UTC milliseconds and timezoneOffset in JavaScript isn't entirely possible. Because TimezoneOffset only provides Offset and Some timezones have DST changes throughout the year.

You can still do something like that:

function getLocalTimeFromUTC(utcMillis, timezoneOffset) {
  // 1. Create a Date object from UTC milliseconds
  const date = new Date(utcMillis);

  // 2. Adjust for timezone offset (in minutes)
  date.setMinutes(date.getMinutes() + timezoneOffset);

  // 3. Extract local year
  const year = date.getFullYear();

  // 4. Local time with potential DST ambiguity (consider libraries for advanced handling)
  const localTime = date.toLocaleTimeString();

  return { year, localTime };
}
4
  • 1
    "Because TimezoneOffset only provides Offset and Some timezones have DST changes throughout the year." that should be included in the offset. At least if the offset is not related to when the timestamp points to, then it's useless - answering something like "What was the exact local time six months ago given the current offset" is just madness.
    – VLAZ
    Commented Jul 9 at 17:47
  • Other than that, new Date(utcMillis) gives you a date which already has the current timezone offset applied (at least the one JS knows about). Adding extra offset and then trying to get the local time out of it is an error, you actually time shifter twice - first with local offset (taken from the environment automatically) second by adding timezoneOffset. At best this would work if you're in the UK in the winter, since the local offset is then zero. But it starts being off by an hour in the summer.
    – VLAZ
    Commented Jul 9 at 17:50
  • As @VLAZ says, the offset provided should be the one that applies for the particular date and time. You can't necessarily determine the timezone from the offset. Your conversion of utcMillis is OK, to apply the offset consider using date.toLocaleString(lang, {timeZone:'Etc/GMT<offset>'} where <offset> is the offset in whole hours and reversed sign (west is +ve and east is -ve so -04:00 becomes Etc/GMT+4). toLocaleString is supposed to be POSIX compliant, but unfortunately only works with whole hour offsets.
    – RobG
    Commented Jul 10 at 8:35
  • Oh, your method would work if you use UTC methods instead of local (get/setUTCMinutes, getUTCHours) because that's literally what the offset is: the hours and minutes local time differs from UTC.
    – RobG
    Commented Jul 10 at 10:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.