Problem:
I need to get the date for a time zone with javascript but Date instances get the date of the time zone in which the user is located.
This is the code I used:
const date = new Date();
let year = date.getFullYear();
let month = date.getMonth();
let day = date.getDate();
Note: I need an answer without the use of jquery.
Solution:
You can specify a time zone when using toLocaleString
, toLocaleDateString
, or toLocaleTimeString
.
For example:
const now = new Date();
const s = now.toLocaleDateString(undefined, { timeZone: 'America/New_York' });
console.log(s);
The undefined
in the above code indicates to return the resulting string in a format appropriate for the user’s current language.
You can also specify a time zone when using Intl.DateTimeFormat
directly, which offers further capabilities such as getting each part separately with formatToParts
. For example:
function getDateValues(date, timeZone) {
const fmt = new Intl.DateTimeFormat('en', { timeZone });
const parts = fmt.formatToParts(date);
let year, month, day;
for (const part of parts) {
switch (part.type) {
case 'year':
year = parseInt(part.value);
break;
case 'month':
// note, months are 1-12 (not 0-11 like Date.getMonth)
month = parseInt(part.value);
break;
case 'day':
day = parseInt(part.value);
break;
}
}
return {year, month, day};
}
const now = new Date();
const values = getDateValues(new Date(), 'America/New_York');
console.log(values);
Note in this case, I specify English ('en')
for the language, so that I can be assured the resulting strings contain parsable numbers.