JavaScript Dates
JavaScript Dates
Section titled “JavaScript Dates”The Date object in JavaScript allows you to work with dates and times, including years, months, days, hours, minutes, seconds, and milliseconds.
JavaScript Date Representations
Section titled “JavaScript Date Representations”A JavaScript date can be represented in various ways:
As a string (human-readable, but format varies by locale and method):
const currentDateString = new Date().toString();// Example output: "Mon Jul 22 2024 10:30:00 GMT+0200 (Central European Summer Time)"
const isoDateString = new Date().toISOString();// Example output: "2024-07-22T08:30:00.000Z" (UTC timezone, highly recommended for data interchange)As a number (timestamp): milliseconds since January 1, 1970, 00:00:00 UTC (the Unix Epoch).
const timestamp = Date.now(); // Current timestamp// orconst timestampFromDateObject = new Date().getTime();// Example output: 1721637000000Displaying Dates in HTML
Section titled “Displaying Dates in HTML”To display dates in an HTML document, you typically get or create a Date object and then set the textContent or innerHTML of an HTML element. Avoid using document.write().
<!-- HTML --><p>Current Date: <span id="date-display"></span></p>
<script> const dateDisplayElement = document.getElementById('date-display'); if (dateDisplayElement) { dateDisplayElement.textContent = new Date().toLocaleDateString(); // Or .toString(), .toUTCString(), etc. }</script>The script above finds an element with id="date-display" and sets its text content to the current date, formatted according to the user’s locale settings.
You will learn more about formatting dates for display later. For complex date formatting and manipulation, consider using dedicated libraries like date-fns or Luxon. |
|---|
Creating Date Objects
Section titled “Creating Date Objects”Date objects are created using the new Date() constructor.
A date consists of a year, a month (0-11), a day, an hour, a minute, a second, and milliseconds.
There are several ways to initialize a date:
new Date() // Current date and timenew Date(milliseconds) // Milliseconds since Unix Epochnew Date(dateString) // Parses a date string (e.g., "2024-07-22T10:00:00Z")new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)Using new Date() creates a new date object with the current date and time:
const now = new Date();// In an HTML context:// const demoElement = document.getElementById("demo");// if (demoElement) demoElement.textContent = now.toString();console.log(now.toString());Using new Date(dateString) creates a new date object from a recognized date string format. ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ) is generally the most reliable.
const specificDate = new Date("2023-10-26T14:30:00");console.log(specificDate.toString());| Parsing date strings can be unreliable if the format is ambiguous. Prefer ISO 8601 or provide explicit date components. |
|---|
Using new Date(milliseconds) creates a date object based on a timestamp (milliseconds since Jan 1, 1970 UTC).
const oneDayInMilliseconds = 24 * 60 * 60 * 1000;const dayAfterEpoch = new Date(oneDayInMilliseconds);console.log(dayAfterEpoch.toUTCString()); // Fri, 02 Jan 1970 00:00:00 GMT| JavaScript dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC). One day contains 86,400,000 milliseconds. |
|---|
Using new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) creates a date with specified components. Remember that months are 0-indexed (January is 0, December is 11).
const eventDate = new Date(2024, 6, 22, 10, 30, 0, 0); // July 22, 2024, 10:30:00console.log(eventDate.toString());You can omit trailing arguments; they will default to 0 (or 1 for day). For example, to specify only year, month, and day:
const justDate = new Date(2024, 0, 15); // January 15, 2024, 00:00:00console.log(justDate.toString());| JavaScript counts months from 0 to 11. January is 0, December is 11. This is a common source of errors for beginners. |
|---|
Date Methods
Section titled “Date Methods”Once a Date object is created, numerous methods allow you to get and set its components (year, month, day, hour, etc.), in either local time or UTC.
Examples: getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds(), getMilliseconds(), getTime(), setTime(), and their UTC counterparts (getUTCFullYear(), etc.).
| Date methods are covered in detail in a later chapter. Refer to MDN Web Docs: Date for a full list. |
|---|
Displaying Dates: Common Formatting Methods
Section titled “Displaying Dates: Common Formatting Methods”When a Date object is used in a context requiring a string (e.g., textContent), it’s often implicitly converted using its toString() method.
const d = new Date();// const demoElement = document.getElementById("demo");// if (demoElement) demoElement.textContent = d; // Implicitly calls d.toString()console.log(d.toString());The toUTCString() method converts a date to a string using the UTC time standard.
const d_utc = new Date();console.log(d_utc.toUTCString());// Example: Mon, 22 Jul 2024 08:30:00 GMTThe toDateString() method converts the date portion to a more readable, human-friendly string.
const d_date = new Date();console.log(d_date.toDateString());// Example: Mon Jul 22 2024Other useful formatting methods include toLocaleDateString(), toLocaleTimeString(), and toLocaleString() which respect the user’s local conventions.
const d_locale = new Date();console.log(d_locale.toLocaleDateString()); // e.g., 7/22/2024 (US) or 22/07/2024 (UK)console.log(d_locale.toISOString()); // e.g., 2024-07-22T08:30:00.000Z (Standard)Date objects are static snapshots in time. The computer’s clock continues to tick, but a Date object, once created, represents a fixed point in time unless its value is explicitly changed using methods like setTime(). |
|---|