Codectionary / Developer documentation / JavaScript

Date: Setting and Formatting

Setter methods like setFullYear() and setDate() modify a Date object in place. Formatting methods convert a Date into a readable string: toDateString() and toTimeString() give simple readable formats, toISOString() gives the standardized ISO 8601 format (useful for APIs), and toLocaleDateString() formats according to a locale's conventions.

Syntax

date.setFullYear(year)
date.toISOString()
date.toLocaleDateString()

Examples

Setter Methods

Modifying parts of an existing Date object.

const date = new Date(2024, 0, 1); // January 1, 2024

date.setFullYear(2025);
date.setMonth(5); // June (0-indexed)
date.setDate(15);

console.log(date); // June 15, 2025

ISO String - For APIs and Storage

The standardized format, ideal for sending dates to a server.

const date = new Date(2024, 5, 15, 14, 30);
console.log(date.toISOString());
// "2024-06-15T13:30:00.000Z" (converted to UTC)

Locale-Formatted Display Strings

Formatting dates for human-readable display.

const date = new Date(2024, 5, 15);

console.log(date.toDateString());  // "Sat Jun 15 2024"
console.log(date.toLocaleDateString());        // "6/15/2024" (locale-dependent)
console.log(date.toLocaleDateString("en-GB")); // "15/06/2024"
console.log(date.toLocaleDateString("en-US", {
  weekday: "long", year: "numeric", month: "long", day: "numeric"
})); // "Saturday, June 15, 2024"

Best practices

  • Use toISOString() when sending dates to a server or storing them - it is unambiguous and timezone-standardized (UTC)
  • Use toLocaleDateString() with explicit locale and options for user-facing display, rather than the raw toDateString() output
  • Remember setter methods mutate the Date object in place - copy it first with new Date(originalDate) if you need to preserve the original
  • Be mindful of time zone differences - toISOString() converts to UTC, which can shift the displayed date/time relative to the user's local time

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading