Skip to content

ES6 - Date

JavaScript provides a built-in Date object for working with dates and times. Date objects are created using the new Date() constructor.

Once a Date object is created, numerous methods allow you to get and set its components (year, month, day, hour, minute, second, millisecond), using either local time or Coordinated Universal Time (UTC).

The ECMAScript standard specifies that the Date object can represent any date and time with millisecond precision within a range of approximately ±273,785 years from January 1, 1970, UTC.

You can create a Date object in several ways:

// 1. Without arguments: creates a Date object for the current date and time.
const now = new Date();
console.log('Current time:', now.toString());
// 2. With milliseconds: creates a Date object from milliseconds since the UNIX epoch (Jan 1, 1970, UTC).
const epochTime = new Date(0); // The epoch itself
console.log('Epoch:', epochTime.toUTCString());
const specificTime = new Date(1678886400000); // Example: March 15, 2023
console.log('Specific time from ms:', specificTime.toString());
// 3. With a date string: creates a Date object by parsing a string (format can be tricky and browser-dependent, ISO 8601 "YYYY-MM-DDTHH:mm:ss.sssZ" is recommended).
const dateFromStringISO = new Date('2024-07-26T10:30:00Z'); // ISO 8601 format (UTC)
console.log('From ISO String:', dateFromStringISO.toUTCString());
const dateFromStringSimple = new Date('2024-07-26'); // Interpreted as UTC if only date, or local if time is also present without Z
console.log('From Simple Date String:', dateFromStringSimple.toDateString());
// 4. With individual date and time components (year, monthIndex, day, hours, minutes, seconds, milliseconds) - local time.
// Note: month is 0-indexed (0 for January, 11 for December).
const specificComponents = new Date(2024, 6, 26, 14, 45, 30, 500); // July 26, 2024, 2:45:30.500 PM local time
console.log('From Components:', specificComponents.toString());

Important Note on Date Strings:

Parsing date strings with new Date(dateString) can be unreliable due to differences in browser implementations and locale settings. It’s generally safer to use the ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ) or provide individual date components. For complex date parsing and manipulation, consider using a dedicated library like date-fns or Luxon.

Date Object Properties (Static and Prototype)

Section titled “Date Object Properties (Static and Prototype)”

The Date object itself has static properties (like Date.now()) and its instances (objects created with new Date()) have methods inherited from Date.prototype.

  • Date.now() (Static Method): Returns the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC.
  • Date.parse(dateString) (Static Method): Parses a string representation of a date and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Like constructor, parsing can be unreliable).
  • Date.UTC(year, monthIndex[, day[, hours[, minutes[, seconds[, ms]]]]]) (Static Method): Accepts comma-delimited date parameters and returns the number of milliseconds since January 1, 1970, 00:00:00, Universal Time.
  • constructor: A property of an instance, refers to the Date function that created the instance.
  • prototype: A property of the Date constructor, allowing addition of properties and methods to all Date instances (generally not recommended to modify built-in prototypes).

Here’s a list of commonly used methods available on Date instances. Most get methods have corresponding set methods (e.g., getFullYear() and setFullYear()). There are also UTC equivalents for most (e.g., getUTCFullYear()).

MethodDescription (Local Time unless specified)
getDate() / setDate(day)Gets/sets the day of the month (1-31) for the specified date according to local time.
getDay()Gets the day of the week (0 for Sunday, 1 for Monday, …, 6 for Saturday) for the specified date according to local time.
getFullYear() / setFullYear(year[, month[, day]])Gets/sets the full year (4 digits) for the specified date according to local time.
getHours() / setHours(hours[, min[, sec[, ms]]])Gets/sets the hour (0-23) for the specified date according to local time.
getMilliseconds() / setMilliseconds(ms)Gets/sets the milliseconds (0-999) for the specified date according to local time.
getMinutes() / setMinutes(min[, sec[, ms]]])Gets/sets the minutes (0-59) for the specified date according to local time.
getMonth() / setMonth(month[, day])Gets/sets the month (0-11) for the specified date according to local time. (0-indexed!)
getSeconds() / setSeconds(sec[, ms])Gets/sets the seconds (0-59) for the specified date according to local time.
getTime() / setTime(milliseconds)Gets/sets the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC.
getTimezoneOffset()Returns the time-zone offset in minutes for the current locale from UTC. (e.g., UTC-5 returns 300).
toDateString()Returns the “date” portion of the Date as a human-readable string (e.g., “Fri Jul 26 2024”).
toISOString()Returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ). The timezone is always zero UTC offset, as denoted by the suffix “Z”.
toLocaleDateString([locales[, options]])Returns the “date” portion of the Date as a string, using locale conventions.
toLocaleString([locales[, options]])Returns a string representing the date and time, using locale conventions.
toLocaleTimeString([locales[, options]])Returns the “time” portion of the Date as a string, using locale conventions.
toString()Returns a string representing the specified Date object (implementation-dependent format, often includes timezone).
toTimeString()Returns the “time” portion of the Date as a human-readable string (e.g., “14:45:30 GMT+0200 (Central European Summer Time)”).
toUTCString()Converts a date to a string using the UTC timezone convention (e.g., “Fri, 26 Jul 2024 12:45:30 GMT”).
valueOf()Returns the primitive value of a Date object (milliseconds since epoch), same as getTime().
const today = new Date(); // Current date and time
console.log('Full Year:', today.getFullYear());
console.log('Month (0-indexed):', today.getMonth()); // 0 for January, 1 for February...
console.log('Day of Month:', today.getDate());
console.log('Hours:', today.getHours());
console.log('Minutes:', today.getMinutes());
console.log('Seconds:', today.getSeconds());
console.log('Milliseconds since epoch:', today.getTime());
console.log('ISO String:', today.toISOString());
console.log('Locale Date String (US):', today.toLocaleDateString('en-US'));
console.log('Locale Time String (US):', today.toLocaleTimeString('en-US', { hour12: true, hour: 'numeric', minute: '2-digit' }));
// Setting parts of a date
const eventDate = new Date();
eventDate.setMonth(11); // Set month to December (11)
eventDate.setDate(25); // Set day to 25th
console.log('Event Date (Christmas):', eventDate.toDateString());
  • 0-Indexed Months: getMonth() returns 0 for January, 1 for February, …, 11 for December. When setting months with setMonth(), the same 0-indexing applies. This is a frequent source of bugs.
  • Timezones: JavaScript Date objects inherently handle timezones based on the user’s system settings for local time methods. Be mindful of this when working with dates across different regions. UTC methods (getUTCDate(), setUTCHours(), etc.) work with Coordinated Universal Time, avoiding local timezone ambiguities.
  • Date String Parsing: As mentioned, new Date(dateString) can be inconsistent. Prefer ISO 8601 or component-based construction, or use a library for robust parsing.
  • Mutability: Date objects are mutable. Methods like setDate(), setFullYear() modify the original Date object. If you need to preserve the original date, create a new Date object from it first (e.g., const newDate = new Date(oldDate.getTime());).

For more advanced date and time manipulations, internationalization, or time zone handling, consider using well-established libraries like date-fns, Day.js, or Luxon. They offer more features and a more developer-friendly API than the native Date object.