JavaScript
// Method 1: Get timezone offset
function getTimezoneOffset() {
const offset = new Date().getTimezoneOffset();
const hours = Math.floor(Math.abs(offset) / 60);
const minutes = Math.abs(offset) % 60;
const sign = offset > 0 ? '-' : '+';
return `${sign}${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
}
console.log('Timezone offset:', getTimezoneOffset());
// Method 2: Convert to UTC
function toUTC(date) {
return new Date(date.toUTCString());
}
const localDate = new Date();
console.log('Local:', localDate);
console.log('UTC:', toUTC(localDate));
// Method 3: Convert to specific timezone (using Intl)
function toTimezone(date, timezone) {
return new Date(date.toLocaleString('en-US', { timeZone: timezone }));
}
const date = new Date();
console.log('New York:', toTimezone(date, 'America/New_York'));
console.log('Tokyo:', toTimezone(date, 'Asia/Tokyo'));
console.log('London:', toTimezone(date, 'Europe/London'));
// Method 4: Format with timezone
function formatWithTimezone(date, timezone) {
return new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
}).format(date);
}
console.log('NY formatted:', formatWithTimezone(date, 'America/New_York'));
// Method 5: List available timezones
function getTimezones() {
return Intl.supportedValuesOf('timeZone');
}
console.log('Available timezones:', getTimezones().slice(0, 5));
// Method 6: Convert between timezones
function convertTimezone(date, fromTZ, toTZ) {
const fromDate = new Date(date.toLocaleString('en-US', { timeZone: fromTZ }));
const toDate = new Date(date.toLocaleString('en-US', { timeZone: toTZ }));
return toDate;
}
const nyDate = new Date('2024-01-15T12:00:00');
const tokyoDate = convertTimezone(nyDate, 'America/New_York', 'Asia/Tokyo');
console.log('NY to Tokyo:', tokyoDate);Output
Timezone offset: +00:00 Local: 2024-01-15T10:30:45.123Z UTC: 2024-01-15T10:30:45.123Z New York: 2024-01-15T05:30:45.123Z Tokyo: 2024-01-15T19:30:45.123Z London: 2024-01-15T10:30:45.123Z NY formatted: 01/15/2024, 05:30:45 Available timezones: ["Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers", "Africa/Asmara"] NY to Tokyo: 2024-01-15T19:00:00.000Z
Timezone conversion handles different zones.
Timezone Offset
- getTimezoneOffset(): Minutes from UTC
- Negative = ahead of UTC
- Positive = behind UTC
UTC Methods
- toUTCString(): UTC string
- getUTC* methods: UTC components
- Work with UTC timezone
Intl API
- Intl.DateTimeFormat: Format with timezone
- toLocaleString with timeZone option
- List timezones: supportedValuesOf
Conversion
- Convert between timezones
- Handle daylight saving
- Use Intl for accuracy
Best Practices
- Store dates in UTC
- Convert for display
- Use Intl.DateTimeFormat
- Handle DST changes