JavaScript Dates
The Date object lets you work with dates and times, from the current moment to any point in the past or future.
Creating a Date object
JavaScript represents dates and times with the built-in Date object. You create one using the new keyword. Calling new Date() with no arguments gives you the current date and time based on the environment running the code. You can also build a Date for a specific moment by passing a timestamp, a date string, or individual date parts.
- new Date() creates a Date for the current moment.
- new Date(milliseconds) creates a Date a number of milliseconds after January 1, 1970.
- new Date(dateString) parses a text string into a Date.
- new Date(year, month, day, hours, minutes, seconds, ms) builds a Date from parts.
Different ways to create dates
<!DOCTYPE html>
<html>
<body>
<h2>Creating Date Objects</h2>
<script>
const now = new Date();
const fromString = new Date("2026-07-15");
const fromParts = new Date(2026, 6, 15, 9, 30, 0); // month 6 = July
const fromMillis = new Date(0); // Jan 1, 1970 UTC
console.log(now);
console.log(fromString);
console.log(fromParts);
</script>
</body>
</html>How dates are stored
Internally, every Date is stored as a single number: the count of milliseconds since midnight on January 1, 1970, in Coordinated Universal Time (UTC). This reference point is known as the Unix epoch. Because a date is just a number under the hood, you can compare two dates or measure the gap between them using ordinary arithmetic.
Comparing and measuring dates
<!DOCTYPE html>
<html>
<body>
<h2>Comparing Dates</h2>
<script>
const start = new Date("2026-01-01");
const end = new Date("2026-07-15");
const diffMs = end - start; // difference in milliseconds
const diffDays = diffMs / (1000 * 60 * 60 * 24);
console.log(diffDays); // number of days between the two dates
console.log(end > start); // true
</script>
</body>
</html>Date input formats
When you pass a string to the Date constructor, the format matters. The ISO 8601 format (YYYY-MM-DD) is the most reliable and is understood consistently across browsers. Other formats may be interpreted differently depending on the environment, so it is best to stick with ISO strings when parsing dates from text.
Displaying a date
A Date object has several methods for producing readable text. toString gives a full description, toDateString shows just the date portion, and toISOString returns the standardized UTC format that is useful for storing or transmitting dates. Choosing the right one depends on whether you want machine-friendly or human-friendly output.
Turning a date into text
<!DOCTYPE html>
<html>
<body>
<h2>Formatting Dates</h2>
<script>
const d = new Date("2026-07-15T09:30:00Z");
console.log(d.toDateString()); // e.g. "Wed Jul 15 2026"
console.log(d.toISOString()); // "2026-07-15T09:30:00.000Z"
console.log(d.toLocaleDateString()); // locale-specific format
</script>
</body>
</html>Exercise: JavaScript Dates
What value does Date.now() return?