🌱BeginnerJavaScript Fundamentals
Date and Time
The Date object creating dates, reading parts, comparing, formatting, and working with timestamps.
Overview
JavaScript's built-in `Date` object represents a point in time as milliseconds since the Unix epoch (1 January 1970, 00:00:00 UTC). It's how you get the current time, parse date strings, compare dates, and format output.
`new Date()` creates a Date for right now. `Date.now()` returns the current timestamp in milliseconds as a plain number useful for performance timing or storing timestamps. You can construct a specific date with `new Date(year, monthIndex, day, ...)` note that months are **zero-indexed** (0 = January, 11 = December).
For display, `.toLocaleDateString()` and `.toLocaleTimeString()` format a date according to the user's locale. For storage and APIs, use `.toISOString()` which produces a standard UTC string like `"2024-06-15T10:30:00.000Z"`.
**Note**: For serious date manipulation (parsing, timezones, arithmetic), prefer a library like `date-fns` or `Temporal` (the upcoming standard) over raw Date arithmetic.
Key Points
- •`new Date()` current date/time; `Date.now()` current timestamp in ms (no object)
- •`new Date(year, monthIndex, day, h, m, s)` specific date; months are 0-indexed
- •`new Date("2024-06-15")` parse ISO string (use ISO format to avoid timezone issues)
- •`.getFullYear()`, `.getMonth()` (0-11), `.getDate()` (1-31), `.getDay()` (0=Sun, 6=Sat)
- •`.getHours()`, `.getMinutes()`, `.getSeconds()`, `.getMilliseconds()`
- •`.toISOString()` standard format for storage/APIs: `"2024-06-15T00:00:00.000Z"`
- •`.toLocaleDateString(locale, options)` locale-aware formatting
- •Timestamps: subtract two Date objects (or `Date.now()` values) to get milliseconds difference
Examples
Creating and reading dates
const now = new Date();
console.log(now); // Current date/time
// Read parts
console.log(now.getFullYear()); // e.g. 2024
console.log(now.getMonth()); // 0–11 (0 = Jan!)
console.log(now.getMonth() + 1); // human month 1–12
console.log(now.getDate()); // day of month 1–31
console.log(now.getDay()); // 0=Sun, 1=Mon, ..., 6=Sat
console.log(now.getHours());
console.log(now.getMinutes());
// Specific date June 15 2024
const birthday = new Date(2024, 5, 15); // month 5 = June
console.log(birthday.getMonth() + 1); // 6
console.log(birthday.getFullYear()); // 2024
// From ISO string (timezone-safe)
const iso = new Date("2024-06-15T12:00:00");
console.log(iso.toISOString());Formatting dates for display
const date = new Date("2024-06-15");
// ISO format for storage and APIs
console.log(date.toISOString()); // "2024-06-15T00:00:00.000Z"
// Locale-aware display
console.log(date.toLocaleDateString("en-US")); // "6/15/2024"
console.log(date.toLocaleDateString("en-GB")); // "15/06/2024"
console.log(date.toLocaleDateString("de-DE")); // "15.6.2024"
// Custom format with options
const opts = { year: "numeric", month: "long", day: "numeric" };
console.log(date.toLocaleDateString("en-US", opts)); // "June 15, 2024"
// Manual formatting
function formatDate(d) {
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, "0");
const day = String(d.getDate()).padStart(2, "0");
return `${y}-${m}-${day}`;
}
console.log(formatDate(new Date())); // "2024-06-15"Date arithmetic with timestamps
// Date.now() milliseconds since epoch
const start = Date.now();
// ... do some work ...
const end = Date.now();
console.log(`Elapsed: ${end - start}ms`);
// Days between two dates
function daysBetween(d1, d2) {
const ms = Math.abs(d2 - d1); // dates subtract as numbers
return Math.floor(ms / (1000 * 60 * 60 * 24));
}
const jan1 = new Date("2024-01-01");
const mar15 = new Date("2024-03-15");
console.log(daysBetween(jan1, mar15)); // 74
// Add 30 days to today
const future = new Date();
future.setDate(future.getDate() + 30);
console.log(future.toLocaleDateString());Common Mistakes
- Month is zero-indexed `new Date(2024, 0, 1)` is January 1, `new Date(2024, 11, 31)` is December 31
- Parsing ambiguous date strings `new Date("06/15/2024")` is unreliable across browsers; always use ISO format `"2024-06-15"`
- Mutating a Date with setter methods (`.setDate()`) creates bugs when the same Date object is referenced elsewhere; create a new Date instead
Note
For displaying timestamps to users, always use `.toLocaleString()` so the browser formats the date in the user's local timezone and language. For storing or sending dates, always use `.toISOString()` (UTC, unambiguous).
Exercises
Write JavaScript code to solve each exercise. Run it and check your output.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4