TypeScript – Date Object: Mastering Date and Time with Detailed Code Explanations

Introduction – What Is the Date Object in TypeScript?

The Date object in TypeScript, inherited from JavaScript, provides a way to create, manipulate, compare, and format date and time values. With TypeScript’s static typing and IntelliSense support, working with dates becomes safer and easier to manage β€” especially in large-scale applications.

In this article, you’ll learn:

  • How to create a Date object in multiple ways
  • How to access and modify parts of a date
  • How to compare and format dates
  • Real-world use cases for date operations

What Is the Date Object?

The Date object stores a specific point in time, measured in milliseconds since January 1, 1970, UTC (known as the Unix epoch).

const now: Date = new Date();
console.log(now); // Outputs the current date and time

Explanation:

  • new Date() creates a new date object representing the current system time.
  • TypeScript infers the type as Date when using new Date().

Different Ways to Create a Date Object

1️⃣ Current Date and Time

const current: Date = new Date();
console.log(current); // e.g., 2025-05-26T09:15:00.000Z

Creates a new Date object with the current time.


2️⃣ From a Date String

const fromString: Date = new Date("2024-12-25T00:00:00");
console.log(fromString); // Outputs: 2024-12-25T00:00:00.000Z

Parses an ISO 8601 string to a valid Date object.


3️⃣ From Individual Components

const specific: Date = new Date(2024, 11, 25); // December 25, 2024
console.log(specific); // 2024-12-25T00:00:00.000Z

Explanation:

  • new Date(year, monthIndex, day) accepts numeric values.
  • Months are zero-based, so 11 = December.

4️⃣ From Timestamp

const timestampDate: Date = new Date(1700000000000);
console.log(timestampDate); // Outputs date corresponding to timestamp

Converts a Unix timestamp (in milliseconds) into a Date.


Accessing Date Components

You can retrieve parts of a date using “getter” methods:

const date = new Date("2025-05-26T12:30:00");

console.log(date.getFullYear());  // 2025
console.log(date.getMonth());     // 4 (May)
console.log(date.getDate());      // 26
console.log(date.getDay());       // 1 (Monday)
console.log(date.getHours());     // 12
console.log(date.getMinutes());   // 30
console.log(date.getSeconds());   // 0

Explanation:

  • getFullYear() returns the year (e.g., 2025).
  • getMonth() returns 0-based month (May = 4).
  • getDay() returns weekday (0 = Sunday, 1 = Monday).

Setting Date and Time Values

You can update a Date object using “setter” methods.

const date = new Date();
date.setFullYear(2030);
date.setMonth(0); // January
date.setDate(15);

console.log(date); // Outputs: 2030-01-15T...

Explanation:

  • setFullYear(2030) sets the year.
  • setMonth(0) sets January.
  • setDate(15) sets the 15th day of the month.

Performing Date Arithmetic

Adding Days to a Date

function addDays(date: Date, days: number): Date {
  const result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

const today = new Date("2025-05-26");
const nextWeek = addDays(today, 7);
console.log(nextWeek); // 2025-06-02

Explanation:

  • getDate() retrieves the current day.
  • setDate(currentDay + days) moves the date forward.

Subtracting Hours from a Date

function subtractHours(date: Date, hours: number): Date {
  return new Date(date.getTime() - hours * 60 * 60 * 1000);
}

const updated = subtractHours(new Date("2025-05-26T12:00:00"), 3);
console.log(updated); // 2025-05-26T09:00:00.000Z

Explanation:

  • Converts hours to milliseconds and subtracts from current time.

Comparing Dates

const a = new Date("2025-01-01");
const b = new Date("2025-12-31");

console.log(a < b); // true
console.log(a.getTime() === b.getTime()); // false

Explanation:

  • Dates can be compared using relational operators (<, >, ===) by comparing their timestamps.

Formatting Dates

toDateString()

console.log(new Date().toDateString()); // "Mon May 26 2025"

toISOString()

console.log(new Date().toISOString()); // "2025-05-26T09:00:00.000Z"

toLocaleDateString()

console.log(new Date().toLocaleDateString("en-US")); // "5/26/2025"

Explanation:

  • toLocaleDateString() allows locale-specific formatting.
  • toISOString() is great for consistent formatting across systems.

Working with Time Zones

const indiaTime = new Date().toLocaleString("en-IN", {
  timeZone: "Asia/Kolkata"
});

console.log(indiaTime); // "26/5/2025, 2:30:00 pm"

Explanation:

  • Uses toLocaleString() with timeZone option for formatting in a specific region.

Real-World Use Cases

Use CaseDescription
Scheduling tasksCalculate future or past dates
Logging and audit trailsUse toISOString() for timestamps
Age or duration calculationUse date difference logic
Date validation in formsCompare current vs. selected dates
InternationalizationUse locale-based formatting for users

Summary – TypeScript Date Object

The Date object in TypeScript is a robust tool for managing, comparing, and formatting dates and times. With TypeScript’s type checking, you can handle date operations more confidently and avoid common pitfalls.

Key Takeaways:

  • Create dates using new Date() or from strings/timestamps.
  • Use getters like getFullYear() and setters like setDate() to access or modify values.
  • Perform date arithmetic using milliseconds or helper functions.
  • Format dates using toLocaleDateString() or toISOString().
  • Use third-party libraries for advanced manipulation (e.g., date-fns, Luxon).

Real-world relevance:

  • Ideal for date pickers, log timestamps, billing cycles, and globalized apps.

FAQs – TypeScript Date Object

Can I directly compare two Date objects?

Yes. Use date1.getTime() === date2.getTime() or relational operators like date1 < date2.


How do I convert a string to a Date?

const date = new Date("2025-12-25");

TypeScript will parse ISO-compatible strings into valid Date objects.


How to add time to a Date object?

Use methods like setDate() or manipulate getTime() with milliseconds:

date.setDate(date.getDate() + 7); // Adds 7 days

Is there timezone support in TypeScript?

Use toLocaleString() with the timeZone option for formatted strings. For advanced support, consider using libraries like date-fns-tz.


What’s the best way to format dates?

Use:

date.toLocaleDateString("en-US"); // Locale-specific
date.toISOString();              // Universal

For custom formats, use a date utility library.


Share Now :
Share

TypeScript β€” Date Object

Or Copy Link

CONTENTS
Scroll to Top