Enhanced date parsing functionality with timezone support for converting various date formats and ISO strings into Date objects with proper timezone handling.
Convert arguments to Date instances with timezone support, extending date-fns parsing capabilities with timezone-aware processing.
/**
* Convert argument to Date instance with timezone support
* @param argument - Value to convert (Date, number timestamp, or ISO string)
* @param options - Parsing options including timezone
* @returns Parsed Date instance
*/
function toDate(
argument: Date | string | number,
options?: ToDateOptionsWithTZ
): Date;Usage Examples:
import { toDate } from "date-fns-tz";
// Parse ISO 8601 strings
const isoDate = toDate('2024-01-15T10:30:00Z');
console.log(isoDate.toISOString()); // "2024-01-15T10:30:00.000Z"
// Parse with timezone context
const dateWithTZ = toDate('2024-01-15T10:30:00', {
timeZone: 'America/New_York'
});
// Parse timestamp
const timestampDate = toDate(1705315800000);
console.log(timestampDate.toISOString()); // "2024-01-15T10:30:00.000Z"
// Parse existing Date objects (pass-through with validation)
const existingDate = toDate(new Date('2024-01-15'));
console.log(existingDate instanceof Date); // trueThe toDate function provides enhanced support for ISO 8601 date strings with various timezone specifications:
import { toDate } from "date-fns-tz";
// Zulu time (UTC)
const utcDate1 = toDate('2024-01-15T10:30:00Z');
const utcDate2 = toDate('2024-01-15T10:30:00.000Z');
console.log(utcDate1.toISOString()); // "2024-01-15T10:30:00.000Z"
console.log(utcDate2.toISOString()); // "2024-01-15T10:30:00.000Z"// Positive offset
const offsetPos = toDate('2024-01-15T10:30:00+05:30');
console.log(offsetPos.toISOString()); // "2024-01-15T05:00:00.000Z"
// Negative offset
const offsetNeg = toDate('2024-01-15T10:30:00-08:00');
console.log(offsetNeg.toISOString()); // "2024-01-15T18:30:00.000Z"
// Various offset formats
const formats = [
'2024-01-15T10:30:00+05:30', // Standard format
'2024-01-15T10:30:00+0530', // Compact format
'2024-01-15T10:30:00+05', // Hour only
];
formats.forEach(dateStr => {
const parsed = toDate(dateStr);
console.log(`${dateStr} -> ${parsed.toISOString()}`);
});import { toDate } from "date-fns-tz";
// Parse local time string with timezone context
const localWithTZ = toDate('2024-01-15T10:30:00', {
timeZone: 'America/New_York'
});
// This interprets 10:30 AM as New York time
console.log(localWithTZ.toISOString());
// Compare with different timezones
const sameTimeInTokyo = toDate('2024-01-15T10:30:00', {
timeZone: 'Asia/Tokyo'
});
const sameTimeInUTC = toDate('2024-01-15T10:30:00', {
timeZone: 'UTC'
});
console.log('NY:', localWithTZ.toISOString());
console.log('Tokyo:', sameTimeInTokyo.toISOString());
console.log('UTC:', sameTimeInUTC.toISOString());import { toDate } from "date-fns-tz";
// Unix timestamp (milliseconds)
const msTimestamp = toDate(1705315800000);
console.log(msTimestamp.toISOString()); // "2024-01-15T10:30:00.000Z"
// Unix timestamp (seconds) - multiply by 1000
const secTimestamp = toDate(1705315800 * 1000);
console.log(secTimestamp.toISOString()); // "2024-01-15T10:30:00.000Z"
// Date.now() result
const nowTimestamp = toDate(Date.now());
console.log(nowTimestamp instanceof Date); // trueimport { toDate } from "date-fns-tz";
// Pass through existing Date objects
const existingDate = new Date('2024-01-15T10:30:00Z');
const processedDate = toDate(existingDate);
console.log(existingDate === processedDate); // false (new instance)
console.log(existingDate.getTime() === processedDate.getTime()); // true (same time)
// Validate and clean Date objects
const invalidDate = new Date('invalid');
const cleanedDate = toDate(invalidDate);
console.log(isNaN(cleanedDate.getTime())); // true (still invalid, but processed)interface ToDateOptionsWithTZ {
/**
* IANA time zone identifier or offset string
* Used when parsing local time strings without timezone specification
*/
timeZone?: string;
/**
* Number of additional digits for extended year representation
* Supports years beyond the standard 4-digit format
*/
additionalDigits?: 0 | 1 | 2;
}import { toDate } from "date-fns-tz";
// Extended year formats with additional digits
const options = { additionalDigits: 2 };
// 6-digit years
const extendedYear = toDate('+012024-01-15T10:30:00Z', options);
console.log(extendedYear.getFullYear()); // 12024
// Negative years (BC dates)
const bcDate = toDate('-001000-07-15T12:00:00Z', options);
console.log(bcDate.getFullYear()); // -1000import { toDate } from "date-fns-tz";
// Processing API responses with mixed date formats
interface ApiResponse {
created_at: string;
updated_at: number;
scheduled_for?: string;
}
function processApiResponse(response: ApiResponse) {
return {
created: toDate(response.created_at),
updated: toDate(response.updated_at),
scheduled: response.scheduled_for ? toDate(response.scheduled_for) : null,
};
}
const apiData = {
created_at: '2024-01-15T10:30:00Z',
updated_at: 1705315800000,
scheduled_for: '2024-01-16T14:00:00+05:30',
};
const processed = processApiResponse(apiData);
console.log(processed.created.toISOString());
console.log(processed.updated.toISOString());
console.log(processed.scheduled?.toISOString());import { toDate } from "date-fns-tz";
// Processing user form input with timezone context
interface FormData {
eventDate: string;
eventTime: string;
userTimezone: string;
}
function processEventForm(formData: FormData): Date {
// Combine date and time strings
const dateTimeString = `${formData.eventDate}T${formData.eventTime}:00`;
// Parse with user's timezone context
return toDate(dateTimeString, { timeZone: formData.userTimezone });
}
const form = {
eventDate: '2024-01-15',
eventTime: '14:30',
userTimezone: 'America/Los_Angeles',
};
const eventDate = processEventForm(form);
console.log(eventDate.toISOString()); // UTC equivalent of 2:30 PM PSTimport { toDate } from "date-fns-tz";
// Normalize various date formats from database
interface DatabaseRecord {
id: number;
date_field: string | number | Date;
}
function normalizeDatabaseDates(records: DatabaseRecord[]): DatabaseRecord[] {
return records.map(record => ({
...record,
date_field: toDate(record.date_field),
}));
}
const dbRecords = [
{ id: 1, date_field: '2024-01-15T10:30:00Z' },
{ id: 2, date_field: 1705315800000 },
{ id: 3, date_field: new Date('2024-01-15') },
];
const normalized = normalizeDatabaseDates(dbRecords);
normalized.forEach(record => {
console.log(`Record ${record.id}: ${(record.date_field as Date).toISOString()}`);
});import { toDate } from "date-fns-tz";
// Function to safely parse dates with error handling
function safeDateParse(input: any, options?: ToDateOptionsWithTZ): Date | null {
try {
const parsed = toDate(input, options);
// Check if the result is a valid date
if (isNaN(parsed.getTime())) {
return null;
}
return parsed;
} catch (error) {
console.error('Date parsing failed:', error.message);
return null;
}
}
// Test various inputs
const testInputs = [
'2024-01-15T10:30:00Z', // Valid ISO string
'2024-13-45T10:30:00Z', // Invalid date components
'not-a-date', // Invalid string
1705315800000, // Valid timestamp
null, // Null input
undefined, // Undefined input
];
testInputs.forEach(input => {
const result = safeDateParse(input);
console.log(`Input: ${input}, Result: ${result ? result.toISOString() : 'null'}`);
});
// Validation helper
function isValidDate(date: Date): boolean {
return date instanceof Date && !isNaN(date.getTime());
}
// Type guard for date parsing
function parseAndValidate(input: unknown): Date | null {
if (input == null) return null;
try {
const parsed = toDate(input as Date | string | number);
return isValidDate(parsed) ? parsed : null;
} catch {
return null;
}
}import { toDate } from "date-fns-tz";
// Pattern 1: Server timestamps (always UTC)
function parseServerTimestamp(timestamp: string | number): Date {
// Server timestamps are typically UTC
return toDate(timestamp);
}
// Pattern 2: User input (local time with context)
function parseUserDateTime(dateTimeStr: string, userTimezone: string): Date {
return toDate(dateTimeStr, { timeZone: userTimezone });
}
// Pattern 3: Mixed format processing
function parseFlexibleDate(input: string | number | Date, context?: { timeZone?: string }): Date {
// Handle different input types with optional timezone context
if (typeof input === 'string' && !input.includes('T') && context?.timeZone) {
// Plain date string with timezone context
return toDate(`${input}T00:00:00`, { timeZone: context.timeZone });
}
return toDate(input, context);
}
// Usage examples
const serverTime = parseServerTimestamp('2024-01-15T10:30:00Z');
const userTime = parseUserDateTime('2024-01-15T10:30:00', 'Europe/Paris');
const flexibleTime = parseFlexibleDate('2024-01-15', { timeZone: 'Asia/Tokyo' });
console.log('Server:', serverTime.toISOString());
console.log('User:', userTime.toISOString());
console.log('Flexible:', flexibleTime.toISOString());