Reputation: 157
With the hundreds of posts concerning Javascript time questions, I'm certain this has been addressed but I've been through a couple of dozen posts so far and none answer my specific question. I know the offset (-7) and in this particular State in the USA (Arizona) there is NO DST. I just want to display the time in Arizona to any user. All the posts I've reviewed seem to imply that I need to use
return new Date().getTimezoneOffset();
from the local computer as part of my calculations but I'm not sure why that would be necessary? Would this be a viable solution?
const now = new Date();
return {
hour: (now.getUTCHours() -7)
minute: now.getMinutes(),
};
Upvotes: 3
Views: 138
Reputation: 147373
You can use the Intl object and Etc pseudo–timezone for a fixed offset. The EMCAScript version only supports whole hour offsets and the sign is the reverse of convention.
E.g.
console.log('Current time in UTC-7: ' +
new Date().toLocaleString('default',{timeZone:'Etc/GMT+7', hour:'numeric', minute:'2-digit'})
);
console.log('Current time in UTC-7: ' +
new Date().toLocaleTimeString('default',{timeZone:'Etc/GMT+7'})
);
Upvotes: 1
Reputation: 241515
There is no DST in Arizona presently, but that doesn't mean there never will be. Sure, unlikely - but not impossible.
A more robust solution, which also accounts for locale formatting preferences of the user, is as follows:
const s = new Date().toLocaleTimeString(undefined, {
timeZone: 'America/Phoenix'
});
console.log(s);
This will work with any IANA time zone identifier, accounting for DST when applicable, or not - depending on the time zone.
If you want the exact output as in your question, try something like this:
const s = new Date().toLocaleString('en', {
timeZone: 'America/Phoenix',
hour12: false,
hour: 'numeric',
minute: 'numeric'
});
const p = s.split(':');
const o = {
hour: parseInt(p[0]),
minute: parseInt(p[1])
};
console.log(o);
Upvotes: 3
Reputation: 76454
You do not need to getTimezoneOffset
, but you will need to handle the case when the hours are smaller than 7:
const now = new Date();
console.log( {
hour: ((now.getUTCHours() -7) % 24),
minute: now.getMinutes(),
});
Upvotes: 1