Timestamp and Date Handling: A Developer's Guide
Working with Timestamps and Dates
Date and time handling is one of the most common challenges in software development. Inconsistent date formats, timezone issues, and parsing errors can cause serious bugs. This guide covers the essential concepts and best practices.
Unix Timestamp
A Unix timestamp represents the number of seconds (or milliseconds) that have elapsed since January 1, 1970 (the Unix epoch). It is timezone-agnostic and widely used for data storage and APIs.
const nowInSeconds = Math.floor(Date.now() / 1000);
console.log(nowInSeconds); // e.g., 1717852800
const nowInMilliseconds = Date.now();
console.log(nowInMilliseconds); // e.g., 1717852800000
ISO 8601 Format
ISO 8601 is the international standard for date and time representation. It uses the format YYYY-MM-DDTHH:mm:ss.sssZ and includes timezone information.
const now = new Date();
const isoString = now.toISOString();
console.log(isoString); // "2024-06-09T12:00:00.000Z"
Timezone Handling
Timezones are a major source of bugs. Always store times in UTC and convert to local time only for display. Use the Intl.DateTimeFormat API for proper timezone conversion.
const options: Intl.DateTimeFormatOptions = {
timeZone: 'Asia/Tokyo',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
};
const formatter = new Intl.DateTimeFormat('ja-JP', options);
console.log(formatter.format(new Date()));
Date Formatting
JavaScript's built-in Date object has limited formatting options. Consider using libraries like date-fns, dayjs, or Intl.DateTimeFormat for richer formatting.
Date Parsing
Parsing dates from strings can be unreliable. Always use ISO 8601 format for input and avoid the deprecated new Date('MM-DD-YYYY') constructor in favor of explicit parsing.
Best Practices
- Store all timestamps in UTC
- Use ISO 8601 for data exchange
- Never rely on
Dateconstructor with string input - Use timezone-aware libraries for complex operations