Reading history

JavaScript Date: Create, Format and Compare Dates

4 min read 0 views

Learn the JavaScript Date object: creating dates, zero-based months, getDay, toLocaleDateString, ISO strings, days between dates and adding days.

Due dates, countdowns, timestamps and “posted 3 days ago” labels all need dates. JavaScript handles them with the built-in Date object, which stores a single moment in time. This lesson shows how to create dates, read their parts, display them in a friendly format and calculate differences, along with the two traps that catch almost everyone: zero-based months and time zones.

In this lesson you will learn

  • Creating dates for now and for a specific moment
  • Reading parts with getFullYear, getMonth, getDay
  • Formatting with toLocaleDateString and ISO strings
  • Finding the number of days between two dates
  • Adding days and calculating age

Creating and Reading Dates

const now = new Date();                       // this moment
const fromParts = new Date(2026, 11, 20);     // 20 December 2026
const fromString = new Date("2026-12-20T10:30:00");
const fromMs = new Date(0);                   // 1 January 1970 UTC
// Months are counted from 0: January is 0, December is 11
const exam = new Date(2026, 11, 20, 10, 30); // 20 Dec 2026, 10:30 local time

console.log(exam.getFullYear(), exam.getMonth(), exam.getDate());
console.log(exam.getHours() + ":" + exam.getMinutes());
console.log("Day of week (0 = Sunday):", exam.getDay());

console.log(exam.toLocaleDateString("en-GB", {
  weekday: "long", day: "numeric", month: "long", year: "numeric",
}));
console.log(exam.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" }));

// A date in UTC, written in the standard ISO format
const launch = new Date(Date.UTC(2026, 0, 1, 6, 0));
console.log(launch.toISOString());

Output

2026 11 20
10:30
Day of week (0 = Sunday): 0
Sunday, 20 December 2026
10:30 AM
2026-01-01T06:00:00.000Z
  • Months start at 0. new Date(2026, 11, 20) is December, not November, and getMonth() returns 11 for December. Days of the month start at 1 as usual.
  • getDay() gives the day of the week, with 0 for Sunday. Do not confuse it with getDate(), the day of the month.
  • toLocaleDateString() and toLocaleTimeString() format a date for people, using a locale such as "en-GB" and options for which parts to show.
  • toISOString() always gives the standard UTC format used by APIs and databases. Date.UTC() builds a moment in UTC rather than local time.

Date Arithmetic

const start = new Date(2026, 0, 1);
const end = new Date(2026, 11, 25);

// Subtracting dates gives milliseconds
const msPerDay = 24 * 60 * 60 * 1000;
const days = Math.round((end - start) / msPerDay);
console.log("Days between:", days);

// Add 45 days: setDate rolls over months automatically
const due = new Date(2026, 0, 20);
due.setDate(due.getDate() + 45);
console.log("Due date:", due.toDateString());

// Age calculation
function age(birth, today) {
  let years = today.getFullYear() - birth.getFullYear();
  const hadBirthday =
    today.getMonth() > birth.getMonth() ||
    (today.getMonth() === birth.getMonth() && today.getDate() >= birth.getDate());
  if (!hadBirthday) years--;
  return years;
}
console.log("Age:", age(new Date(2005, 7, 30), new Date(2026, 10, 15)));

Output

Days between: 358
Due date: Fri Mar 06 2026
Age: 21
  • Internally a date is a number of milliseconds since 1 January 1970 UTC. Subtracting two dates gives the gap in milliseconds; divide by the milliseconds in a day to get days.
  • Math.round() protects against daylight-saving changes, which make some days 23 or 25 hours long in some countries.
  • setDate(getDate() + 45) adds days. If the result passes the end of a month, JavaScript moves into the next month automatically.
  • The age function subtracts the years, then takes one off if this year’s birthday has not happened yet.
  • Date objects are mutable: setDate() changes the object itself. Copy first with new Date(original) if you need to keep the old value.

Date Method Cheat Sheet

MethodReturns
getFullYear()Four-digit year
getMonth()Month, 0 to 11
getDate()Day of the month, 1 to 31
getDay()Day of the week, 0 (Sunday) to 6
getHours(), getMinutes()Time parts
getTime() / Date.now()Milliseconds since 1970
setDate(), setMonth()…Change a part (mutates)
toISOString()"2026-01-01T06:00:00.000Z"

Common Mistakes

  1. Forgetting months are zero-based, so dates end up one month late.
  2. Parsing "2026-12-20" without a time: a date-only string is treated as UTC midnight, which can show as the previous day in time zones west of UTC.
  3. Changing a date you meant to keep, because set methods modify it.
  4. Building date strings by hand instead of using toLocaleDateString with options.

Practice Exercises

Exercise 1. Print how many days are left until 1 January of next year.

Show answer
const today = new Date();
const newYear = new Date(today.getFullYear() + 1, 0, 1);
const days = Math.ceil((newYear - today) / (24 * 60 * 60 * 1000));
console.log(days + " days to go");

Exercise 2. Write isWeekend(date) for a country where the weekend is Friday and Saturday.

Show answer
const isWeekend = (date) => date.getDay() === 5 || date.getDay() === 6;
console.log(isWeekend(new Date(2026, 10, 13))); // Friday: true

Frequently Asked Questions

How do I get the current timestamp?

Date.now() returns the milliseconds since 1 January 1970 UTC. Divide by 1000 and round down for a Unix timestamp in seconds.

Should I use a date library?

For simple formatting and differences, the built-in Date and Intl APIs are enough. For heavy time-zone work, a library or the newer Temporal API, where supported, makes life easier.

Summary

  • new Date(y, m, d) creates a local date; months run from 0 to 11.
  • Get methods read parts; set methods change them in place.
  • Format with toLocaleDateString for people and toISOString for machines.
  • Subtract dates to get milliseconds, then convert to days.

Next: JavaScript Classes.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *