Topic 33 of 59 JavaScript Asynchronous & Advanced Concepts Interactive Tutorial

JavaScript Dates: Creating, Formatting, Comparing, and Manipulating Time

23 mins read Last updated: 22 Aug 2026 14453 views
Quick Summary & Key Takeaway Target Skill Level: Beginner to Advanced ES6+

Bottom-Line Answer: JavaScript (JS) is a high-level, single-threaded, just-in-time (JIT) compiled programming language with first-class functions that conforms to the ECMAScript specification. It powers dynamic client-side web interactivity alongside HTML and CSS, and executes backend server runtimes via Node.js, Deno, and Bun.

Target Audience: Frontend developers, full-stack engineers, students & QA testers.
Prerequisites: Basic HTML semantics & fundamental CSS styling rules.
Primary Use Cases: Dynamic web UI, DOM manipulation, asynchronous REST APIs, Node.js backend services.

What is JavaScript Dates? Core Concept & Direct Summary

Core Objective & Problem Statement

How do you work with dates and timestamps in JavaScript?

Direct Answer Summary
The Date object (new Date()) manages timestamps based on milliseconds elapsed since Jan 1, 1970 UTC.
Every app deals with time: order timestamps, "posted 2 hours ago," booking systems, birthday reminders, "offer expires in 2 days." And every developer, without exception, has written this bug:
script.js
Run Online
const birthday = new Date(2000, 5, 15);
// June 15, 2000… right?console.log(birthday);// 😱 "May 15, 2000" — WHAT?!

Welcome to JavaScript'sDateobject — powerful, built-in, andfull of quirksthat have been tripping developers since 1995. Months start at 0. Days start at 1. And formatting dates is somehow harder than it should be.

The good news: once you know the handful of rules in this lesson, dates become genuinely easy. You'll learn to create dates, read and change their parts, format them beautifully for any country, compare them, and calculate the difference between two dates. Let's travel through time. ⏳

How Does JavaScript Dates Work? In-Depth Mechanics & Architecture

Months in Date are 0-indexed (Jan = 0, Dec = 11). Use Intl.DateTimeFormat or libraries for complex time zone formatting.

Creating Dates: The Four Ways 🏗️

① Right Now — No Arguments

script.js
Run Online
const now = new Date();
console.log(now);
// Thu Sep 19 2026 14:32:07 GMT+0530 (your current moment)

② From a Date String

script.js
Run Online
const diwali = new Date("2026-11-08");
// ISO format — the reliable one ✅const meeting = new Date("2026-11-08T14:30:00");  // with time attached

⚠️ Stick to ISO format (YYYY-MM-DD):strings like"11/08/2026"parse differently across browsers (is that November 8 or August 11?!). ISO format removes all ambiguity.

③ From Individual Components

script.js
Run Online
// new Date(year, month, day, hours, minutes, seconds)const birthday = new Date(2000, 5, 15, 10, 30);

④ From a Timestamp (Milliseconds)

JavaScript's secret: every date is stored asmilliseconds since January 1, 1970(the "Unix epoch"):

script.js
Run Online
const epoch = new Date(0);
// Jan 1, 1970 — time zero 🕛const someDay = new Date(1700000000000); // a moment 1.7 trillion ms later

🚨 The Month Trap (Read This Twice!)

Back to our opening bug:

script.js
Run Online
new Date(2000, 5, 15);
// May 15 — NOT June!

Months are zero-indexed— January is0, December is11:

You WriteYou Get
0January
1February
5June(not May!)
11December
script.js
Run Online
const june15 = new Date(2000, 5, 15);
// ✅ June 15 (month 5 = June)

Why?A design decision copied from Java in 1995 that can never be fixed without breaking the old web — just liketypeof nullfromLesson 5. Days, years, and hours are normal (1-based);only months are weird. Memorize it once, never get bitten again. 🧠


Reading Date Parts: The Getter Family 📖

script.js
Run Online
const date = new Date("2026-09-19T14:30:45");
console.log(date.getFullYear());
// 2026 — the yearconsole.log(date.getMonth());      // 8 — September (zero-indexed! 🚨)console.log(date.getDate());       // 19 — day of the MONTHconsole.log(date.getDay());        // 6 — day of the WEEK (0 = Sunday!)console.log(date.getHours());      // 14console.log(date.getMinutes());    // 30console.log(date.getSeconds());    // 45console.log(date.getTime());       // 1789… — milliseconds since epoch

⚠️ The Two "Day" Traps

MethodReturnsRange
getDate()Day of themonth1–31
getDay()Day of theweek0–6 (Sunday = 0!)
script.js
Run Online
const d = new Date("2026-09-19");
// a Saturday
console.log(d.getDate());
// 19 — the 19th of Septemberconsole.log(d.getDay());    // 6  — Saturday (Sunday=0, Mon=1, … Sat=6)

Mixing these up is the second-most-common date bug.getDate= calendar day;getDay= weekday.


Changing Dates: The Setter Family ✏️

Every getter has a matching setter:

script.js
Run Online
const event = new Date("2026-09-19T10:00:00");
event.setFullYear(2027);
event.setMonth(11);
// December (0-indexed!)event.setDate(25);event.setHours(18);
console.log(event.toDateString());
// "Fri Dec 25 2027" 🎄

🎁 Bonus Magic: Automatic Overflow Handling

Setters handle rollovers intelligently — exceed a limit and it carries over:

script.js
Run Online
const d = new Date("2026-01-31");
d.setMonth(1);
// Feb 31 doesn't exist…console.log(d.toDateString());  // rolls into early March — handled!
// This makes date math beautifully easy:const today = new Date("2026-09-19");today.setDate(today.getDate() + 30);    // "30 days from now" ✅console.log(today.toDateString());      // "Mon Oct 19 2026" — month rollover automatic!

setDate(getDate() + n)is the standard idiom for "n days from now"— no manual month-length math needed.


Formatting Dates for Humans 🌍

RawDateoutput (Thu Sep 19 2026 14:32:07 GMT+0530) is for machines. For users, usetoLocale*methods — they format forany language and region automatically:

script.js
Run Online
const now = new Date("2026-09-19T14:30:00");
// Local date string:console.log(now.toLocaleDateString("en-IN"));   // "19/9/2026" 🇮🇳console.log(now.toLocaleDateString("en-US"));   // "9/19/2026" 🇺🇸console.log(now.toLocaleDateString("hi-IN"));   // "19/9/2026" (Hindi digits style)
// Local time string:console.log(now.toLocaleTimeString("en-IN"));   // "2:30:00 pm"
// Both:console.log(now.toLocaleString("en-IN"));       // "19/9/2026, 2:30:00 pm"

🎨 Full Control with Options

The options object unlocks beautiful custom formats:

script.js
Run Online
const now = new Date("2026-09-19T14:30:00");
console.log(now.toLocaleDateString("en-IN", {
  weekday: "long", // Saturday  year: "numeric",      // 2026  month: "long",        // September  day: "numeric"        // 19}));// "Saturday, 19 September 2026" ✨
  console.log(now.toLocaleTimeString("en-IN", {
    hour: "2-digit", minute: "2-digit", hour12: true
  }));
  // "02:30 pm"

One built-in method, every locale on Earth — no formatting library needed for most projects.

Other Built-In Formats (Quick Reference)

script.js
Run Online
const d = new Date("2026-09-19T14:30:00");
d.toDateString();
// "Sat Sep 19 2026"d.toISOString();       // "2026-09-19T09:00:00.000Z" — for APIs/databases ✅d.toUTCString();       // "Sat, 19 Sep 2026 09:00:00 GMT"

💡 Remember Lesson 25:JSON.stringifyconverts Dates usingtoISOString()— that's why dates come back from APIs as ISO strings. Revive them withnew Date(savedString).


Comparing Dates ⚖️

Dates can't be compared with===(they're objects — reference comparison from Lesson 5!). But<,>,<=,>=work, because JavaScript converts dates to their millisecond timestamps:

script.js
Run Online
const deadline = new Date("2026-10-01");
const today = new Date("2026-09-19");
console.log(today < deadline);
// true — still time ✅console.log(today > deadline);     // false
// Real-world: is the offer still valid?if (today <= deadline) {  console.log("🎉 Offer is active!");} else {  console.log("😢 Offer expired");}

Checking Exact Equality — Compare Timestamps

script.js
Run Online
const a = new Date("2026-09-19");
const b = new Date("2026-09-19");
console.log(a === b);
// false 😱 — different objects!console.log(a.getTime() === b.getTime());   // true ✅ — same moment!

Rule:===asks "same object?";getTime() ===asks "same moment?". You almost always want the second.


Calculating the Difference Between Dates ⏱️

Subtract two dates → getmilliseconds→ convert to whatever unit you need:

script.js
Run Online
const start = new Date("2026-09-01");
const end = new Date("2026-09-19");
const diffMs = end - start;
// milliseconds betweenconst diffDays = diffMs / (1000 * 60 * 60 * 24);   // ms → s → min → hr → day
console.log(diffDays);
// 18 days

🎂 Real Example: Days Until Your Birthday

script.js
Run Online
function daysUntil(dateString) {
  const target = new Date(dateString);
  const now = new Date();
  const diffMs = target - now;
  const diffDays = Math.ceil(diffMs /(1000 * 60 * 60 * 24));
  // round UP
  if (diffDays < 0) return `That date passed ${-diffDays} days ago!`;
  if (diffDays === 0) return "It's today! 🎉";
  return `${diffDays} days to go! ⏳`;
}console.log(daysUntil("2026-12-25"));
// "97 days to go! ⏳"
console.log(daysUntil("2026-01-01"));
// "That date passed 261 days ago!"

The conversion ladder to memorize:

script.js
Run Online
milliseconds ÷ 1000 → seconds ÷ 60 → minutes ÷ 60 → hours ÷ 24 → days

🛠️ Mini Project: Age Calculator 🎂

script.js
Run Online
// 🎂 Age Calculator — dates, comparison, and math together
function calculateAge(birthdateString) {
  const birth = new Date(birthdateString);
  const today = new Date();
  // Basic year difference:
  let age = today.getFullYear() - birth.getFullYear();
  // ⚠️ But has this year's birthday happened yet?
  const birthdayThisYear = new Date( today.getFullYear(), birth.getMonth(), // their birth month
  birth.getDate() // their birth day
);
  if (today < birthdayThisYear) {
    age--;
    // birthday still coming — subtract one ✅
  } return age;
}console.log(calculateAge("2000-06-15"));
// 25 (before June) or 26 (after)
console.log(calculateAge("2000-12-25"));
// correctly handles December birthdays

The subtle bug this avoids:naively subtracting years calls someone 26 even before their birthday this year. Real-world date logic is full of these edge cases — and now you know how to catch them. 🏆


Common Beginner Mistakes (And Fixes)

❌ Mistake🔍 What Happens✅ Fix
new Date(2000, 5, 15)expecting MayGot June — months are 0-indexed!January = 0, December = 11
ConfusinggetDate()andgetDay()"Weekday: 19" nonsense 😵getDate = month day (1–31), getDay = weekday (0–6)
dateA === dateBfor same-day checkAlways false — object references!a.getTime() === b.getTime()
Parsing"19/09/2026"Browser-dependent chaosUse ISO:"2026-09-19"
Hardcoding format stringsBreaks for other countries/userstoLocaleDateString(locale, options)
Manual month-length math (+30 days)Feb 30th bugs 💀setDate(getDate() + 30)— auto-rollover

Quick Self-Check: Lesson 33 Quiz 🧠

  1. What date doesnew Date(2026, 0, 15)create — and why not what you expected?
  2. What's the difference betweengetDate()andgetDay()?
  3. Why doesnew Date("2026-09-19") === new Date("2026-09-19")returnfalse?
  4. Write one line: format a date as "Saturday, 19 September 2026".
  5. How do you get the number of days between two dates?

(Answers: 1. January 15, 2026 — month 0 is January, since months are zero-indexed · 2. getDate() = day of month (1–31); getDay() = day of week (0=Sunday to 6=Saturday) · 3. They're two different objects in memory — compare moments with getTime() === getTime() · 4.d.toLocaleDateString("en-IN", { weekday: "long", day: "numeric", month: "long", year: "numeric" })· 5. Subtract them (gives milliseconds), then divide by (1000 × 60 × 60 × 24) — round with Math.ceil or Math.floor as needed)

JavaScript Decision Matrix & Syntax Comparison

Understanding the mechanical differences between variable declarations and execution environments is critical for writing performant, bug-free modern JavaScript.

Variable Declarations: var vs let vs const
Feature / Propertyvar (Legacy ES5)let (Modern ES6+)const (Modern ES6+)
ScopeFunction ScopeBlock Scope ({})Block Scope ({})
Hoisting BehaviorHoisted (initialized as undefined)Hoisted (Temporal Dead Zone - ReferenceError)Hoisted (Temporal Dead Zone - ReferenceError)
Reassignable✓ Yes✓ Yes✗ No (Immutable binding)
Redeclarable in Same Scope✓ Yes (Error-prone)✗ No (SyntaxError)✗ No (SyntaxError)
Window Object BindingCreates property on windowDoes not attach to windowDoes not attach to window
Environment Decision Matrix: Browser Client-Side vs Node.js Server-Side
DimensionClient-Side (Web Browser)Server-Side (Node.js / Deno)
Global Objectwindow, document, navigatorglobal, process, globalThis
DOM & UI Manipulation✓ Full access (document.querySelector)✗ No DOM (Headless / Non-UI)
File System & OS Access✗ Blocked (Sandboxed security)✓ Full access (fs, os, child_process)
Primary FocusInteractive UI, animations, client stateREST APIs, microservices, databases, I/O streaming

Runnable JavaScript Code Example & Practical Implementation

script.js
Run Online
let now = new Date();
console.log(now.toISOString());
let specificDate = new Date('2026-09-19');
console.log(specificDate.getFullYear());
// 2026
console.log(specificDate.getMonth());
// 8 (September)

Frequently Asked Questions & Technical Interview Insights

Technical Interview & Viva Questions

Frequently asked questions for frontend & full-stack roles
Q

Q: How do you calculate the difference in days between two Date objects?

A: Subtract timestamps (date2 - date1) to get millisecond difference, then divide by (1000 * 60 * 60 * 24).

Related Tools, Tutorials & Authoritative References

Recommended Interactive Tools

Authoritative Standards & Citations