This answer is based on your comment:
want to display the corresponding local time at the weather location regardless of the user's own time zone. The API provides time as an offset from UTC
The offset from UTC is not the time, it's the bias between UTC and the local time of the location - the time will be in a separate field in the response, or was provided in your request, and is usually in terms of UTC.
You do not need to shift the time by the offset with math. Doing so can lead to many other errors. You can instead provide the original UTC-based timestamp (as presumably returned by your weather API), and format it to a string in a given fixed offset using the timeZone
option of toLocaleString
(and similar Intl
functions).
You do however, need to convert the offset from a number of seconds to an ISO 8601 compliant time zone offset string.
// Formats a Unix timestamp (in terms of milliseconds) to a string,
// to a fixed time zone offset (in terms of seconds).
function formatTimestamp(ts, offsetSeconds) {
const lang = undefined; // use the current language
const timeZone = formatOffset(offsetSeconds);
return new Date(ts).toLocaleString(lang, { timeZone, timeZoneName: 'long' });
}
// Converts offset in seconds to string in ISO 8601 extended format.
// Example: 19800 => "+05:30"
function formatOffset(offsetSeconds) {
const sign = offsetSeconds < 0 ? '-' : '+';
const seconds = Math.abs(offsetSeconds);
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
return sign + ('0' + hours).slice(-2) + ':' + ('0' + minutes).slice(-2);
}
// The current time at UTC+05:30
console.log(formatTimestamp(Date.now(), 19800));
// A specific time at UTC-08:00
console.log(formatTimestamp(1704067200000, -28800));
I included timeZoneName: 'long'
only for demonstration purposes. You can control the format of the output string using any of the options covered in the docs.
Date.now()
which already is your real time. I don't understand the problem. Please examples of dates you get from the API, and what you want as output for them.shiftedDate.toUTCString();
andshiftedDate.toString();
so you can see how the output of the date object is adjusted by your local settings. Also outputcurrentTimeUTC.toUTCString()
/currentTimeUTC.toLocaleString()
to you can see what you're starting with (and how the conversion from the date object is affected).new Date().toString()
will always give the current local time - already "shifted" to the local time zone. Perhaps your weather API is simply telling you what time zone offset is applicable for the time and location of the weather report? It's hard to say without knowing which specific weather API you are using. But even if that's the case, you would still not necessarily need to apply it to the current time, nor shift it yourself manually.Date
object's behavior.