Date and Time in JavaScript: A Practical Guide

Working with dates, timestamps, and timezones in JavaScript.

javascriptcodetutorial

JavaScript Date Handling

JavaScript's Date handling has quirks. Here's what you need to know.

Creating Dates

// Current time
new Date()

// From timestamp (milliseconds!)
new Date(1704067200000)

// From string (ISO 8601)
new Date('2024-01-01T00:00:00Z')

// From components (month is 0-indexed!)
new Date(2024, 0, 1, 0, 0, 0) // Jan 1, 2024

// From Unix timestamp (seconds)
new Date(unixTimestamp * 1000)

Getting Components

const date = new Date();

date.getFullYear() // 2024
date.getMonth() // 0-11 (0 = January!)
date.getDate() // 1-31 (day of month)
date.getDay() // 0-6 (0 = Sunday)
date.getHours() // 0-23
date.getMinutes() // 0-59
date.getSeconds() // 0-59

Formatting

const date = new Date('2024-01-15T14:30:00Z');

// Built-in formatting
date.toISOString() // "2024-01-15T14:30:00.000Z"
date.toLocaleDateString() // "1/15/2024" (locale-dependent)
date.toLocaleTimeString() // "2:30:00 PM"

// With options
date.toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
}); // "Monday, January 15, 2024"

Better: Use a Library

// date-fns (recommended)
import { format, addDays, differenceInDays } from 'date-fns';

format(new Date(), 'yyyy-MM-dd'); // "2024-01-15"
addDays(new Date(), 7);
differenceInDays(date1, date2);

// day.js (lightweight)
import dayjs from 'dayjs';

dayjs().format('YYYY-MM-DD');
dayjs().add(7, 'day');