In javascript, one is given:
- UTC milliseconds since 1970
- timezoneOffset of the local timezone
From the above, how to extract the local time and year implied by the timezoneOffset?
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 };
}
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.
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.