i have a webapp made with react..in which i need to set the default timezone to canada..but i am in india. i would need, new Date() to only return canada time and not india. i have tried using localestring in javascript as follows
const mdt = new Date(
new Date().toLocaleString('en-US', { timeZone: 'America/Edmonton' })
);
but consoling the time ,it is showing as India standard time and not as been set for america/edmonton, although the time for america/edmonton is correct but the timezone should be displayed as well since it is going to the backend as india standard time and getting fetched as india standard time and not canada timezone
CodePudding user response:
There are a couple things you need to understand first:
The javascript Date object is not in any timezone by itself. It stores the timestamp in number of milliseconds elapsed since January 1st 2070 GMT.
When you console.log a Date object, its toString() function is called. This display the time to the user's timezone.
When creating or manipulating a Date object, it will almost always consider in the user's timezone. (Like when you use setHour(), it will be hour in the current timezone)
A universal time can be retrieved from a Date object using the toISOString() this will be the time without any timezone offset.
Now that we know all this, unless you want your users to see a time of a date in a different timezone, you should not have any problem passing dates around. Using toISOString() to send a date to your API, and back, should be enough to make sure that the date will be the same.
The hard part would be if, when a canadian user defines a date at a certain time and that you want to see that exact time, without the timezone differences. In that case, all the above still stands. The only difference is instead of using the toString() function to display a date, you will need to use .toLocaleString('en-US', { timeZone: 'America/Edmonton' })
just as you guessed. But not to create a new date, as the new date created will still be in UTC time no matter what.
CodePudding user response:
As the other answer says, JavaScript Date objects represent a point in time specified by an offset from the Unix epoch (January 1st, 1970), and can't be assigned another timezone as such.
However you can specify a timezone whenever you wish to display the date, using for example, Date.toLocaleString()
.
I would suggest creating a date formatting function, say formatDate()
, that can accept a timezone, but defaults to your desired timezone, in this case 'America/Edmonton'. You'd use this whenever displaying dates.
const defaultTimeZone = 'America/Edmonton';
function formatDate(date, timeZone = defaultTimeZone) {
return date.toLocaleString('default', { timeZone });
}
console.log('Current time:', formatDate(new Date()))
console.log('16:00 UTC (10am Edmonton):', formatDate(new Date('2022-08-10T16:00:00Z')))
.as-console-wrapper { max-height: 100% !important; }