n JavaScript, the timezone is generally determined by the user’s system settings and cannot be directly changed from JavaScript running in a browser. However, you can work with timezones in various ways:
1. Get the User’s Timezone
You can get the user’s current timezone string like this:
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(timeZone); // Example output: "America/New_York"
2. Convert Dates to a Specific Timezone
JavaScript’s built-in Date object always works in the user’s local timezone or UTC, but it doesn’t provide native support for converting dates to arbitrary timezones.
To work with specific timezones, use the Intl.DateTimeFormat API:
const date = new Date();
const options = {
timeZone: 'America/New_York',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
};
const formatter = new Intl.DateTimeFormat('en-US', options);
console.log(formatter.format(date)); // Converts date to America/New_York timezone
3. Use a Library for Advanced Timezone Handling
For complex timezone operations (e.g., converting between timezones, daylight saving adjustments), you should use a library like Luxon or date-fns-tz.
Example with Luxon:
// Make sure to install Luxon: npm install luxon
import { DateTime } from 'luxon';
const dt = DateTime.now().setZone('America/New_York');
console.log(dt.toString()); // Outputs current date and time in New York timezone
Summary
- You cannot set the timezone globally in JavaScript, but you can format or convert dates to specific timezones.
- Use
Intl.DateTimeFormatfor simple timezone formatting. - Use libraries like Luxon for more advanced timezone manipulation.