๐Ÿ—“๏ธ 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 :

Leave a Reply

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

Share

TypeScript โ€” Date Object

Or Copy Link

CONTENTS
Scroll to Top