- Abstract class
- Annotations
- Array
- Asserts
- Casting
- Class
- Conditional types
- Const
- Date object
- Decorators
- Default parameter
- Dictionary
- Enum
- Exclude type
- Extract type
- For loop
- forEach()
- Function
- Generics
- Index signature
- Infer
- Inheritance
- Interface
- Keyof type operator
- Let
- Map type
- Mixin
- Module
- Namespace
- Never
- Object type
- Omit type
- Operator
- Optional parameter
- Partial type
- Pick type
- Promise
- Property
- Readonly type
- Record type
- Required type
- Satisfies operator
- Tuples
- Type alias
- Type assertion
- Type guard
- Type narrowing
- Typeof Type Operator
- Union
- Utility types
- Var
- Void
TYPESCRIPT
TypeScript Date Object: Syntax, Usage, and Practical Examples
The Date
object in TypeScript is used to create, manipulate, and format date and time values. Since TypeScript builds on JavaScript, it uses the native Date
object, but adds type safety and IntelliSense support. You can use it to schedule tasks, display timestamps, calculate durations, and more—all while avoiding common pitfalls through strong typing.
Creating a Date Object in TypeScript
There are several ways to create a new Date
instance.
Get the current date and time:
const now: Date = new Date();
console.log(now);
Create a date from a string:
const dateFromString: Date = new Date("2025-07-04T10:00:00");
Create a date from numeric components:
const independenceDay: Date = new Date(2025, 6, 4); // July is month 6 (0-based)
These approaches give you flexibility when initializing dates based on user input, static values, or external data.
Using Type Annotations
TypeScript lets you annotate variables as Date
to ensure correct usage and access to date methods:
let releaseDate: Date = new Date("2025-01-01");
This prevents accidental assignment of incompatible types and improves code clarity.
Accessing Date Components
You can extract different parts of a date using built-in methods:
const today = new Date();
console.log(today.getFullYear()); // e.g., 2025
console.log(today.getMonth()); // 0–11
console.log(today.getDate()); // 1–31
console.log(today.getDay()); // 0–6 (Sunday to Saturday)
console.log(today.getHours()); // 0–23
console.log(today.getMinutes()); // 0–59
console.log(today.getSeconds()); // 0–59
These functions help you break down a date into usable pieces for comparison, display, or logic.
Modifying a Date
You can update parts of a date using setter methods:
const birthday = new Date();
birthday.setFullYear(1990);
birthday.setMonth(5); // June
birthday.setDate(15);
console.log(birthday.toDateString()); // Fri Jun 15 1990
Setters are useful for constructing custom dates or adjusting values dynamically.
Formatting Dates
You can output a date in various formats using built-in methods:
const now = new Date();
console.log(now.toISOString()); // 2025-07-04T12:00:00.000Z
console.log(now.toDateString()); // Fri Jul 04 2025
console.log(now.toLocaleDateString()); // Locale-specific
For consistent formatting across browsers and regions, use toISOString()
or integrate a formatting library.
Comparing Dates
You can compare two dates directly or by their timestamps:
const start = new Date("2025-07-01");
const end = new Date("2025-07-04");
if (start < end) {
console.log("Start is before end");
}
if (start.getTime() === end.getTime()) {
console.log("Dates are equal");
}
Using .getTime()
ensures an exact millisecond comparison.
Calculating Differences Between Dates
To find the number of days between two dates:
const diffMs = end.getTime() - start.getTime();
const diffDays = diffMs / (1000 * 60 * 60 * 24);
console.log(`Difference: ${diffDays} days`);
This pattern is useful for countdowns, scheduling, or duration tracking.
Adding or Subtracting Time
There are no built-in addDays
or subtractHours
methods, so you modify the time in milliseconds:
const now = new Date();
// Add 1 day
const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000);
// Subtract 1 day
const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
This technique lets you handle date math manually or through helper functions.
Working with Time Zones
TypeScript dates default to the local system time zone, but you can display values in different formats:
console.log(now.toUTCString()); // UTC format
console.log(now.toLocaleString()); // Local system format
Use .getTimezoneOffset()
to understand the user's offset from UTC:
console.log(now.getTimezoneOffset()); // e.g., -120 for UTC+2
For advanced timezone support, consider using libraries.
Handling Invalid Dates
TypeScript won’t stop you from creating a Date
from a bad string, but you can check validity like this:
const invalid = new Date("not-a-date");
if (isNaN(invalid.getTime())) {
console.log("Invalid date");
}
Always validate untrusted or dynamic input to avoid bugs.
External Libraries for Better Date Handling
For advanced formatting, parsing, or timezone support, popular libraries include:
date-fns
import { format } from "date-fns";
console.log(format(new Date(), "yyyy-MM-dd HH:mm:ss"));
Luxon
import { DateTime } from "luxon";
console.log(DateTime.now().toISO()); // 2025-07-04T14:00:00.000+02:00
These libraries simplify working with dates in enterprise-grade applications.
Best Practices
- Use
Date
type annotations for clarity and IntelliSense. - Rely on
.getTime()
for accurate comparisons. - Use libraries for formatting and localization needs.
- Validate input dates before use.
- Handle time zones consistently, especially in global apps.
Summary
The Date
object in TypeScript is a versatile and essential tool for handling time-related data. It supports everything from simple date creation to detailed formatting and arithmetic. By using type annotations and best practices, you can ensure that your code stays clean, safe, and predictable—while libraries like date-fns
or Luxon
extend your capabilities for more complex requirements.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.