Working with Dates and Time in TypeScript: From A to Z

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why Working with Dates in TypeScript Requires Special Attention



Working with dates and time is one of the most common and at the same time tricky tasks in web development. In TypeScript, which is a strictly typed superset of JavaScript, the Date object has inherited all the "quirks" of its predecessor: non-intuitive months (zero-based), mutable methods, and timezone issues. However, by using strict typing and modern libraries, you can write safe, predictable, and readable code for working with time.



In this article, we will cover everything a developer needs to know: from basic date creation to advanced work with timezones and formatting. You will learn how to avoid common mistakes and which tools (built-in and third-party) are best suited for TypeScript projects.



1. Basics: The Date Object and its Typing in TypeScript



Creation and Basic Methods



In TypeScript, as in JavaScript, the built-in Date object is used for working with dates. TypeScript provides ready-made types for it, so no additional definitions are required.



// Creating the current dateconst now: Date = new Date();console.log(now); // 2024-01-15T10:30:00.000Z

// Creating from a string (ISO 8601)const specificDate: Date = new Date('2024-12-31T23:59:59');

// Creating from components (year, month [0-11], day, hours...)const birthday: Date = new Date(1990, 0, 15); // January 15, 1990// Note: month 0 = January!


The Mutability Problem



Methods of the Date object modify the original object. This can lead to unexpected bugs. TypeScript cannot prevent this at the type level, but you can use immutable approaches.



const date = new Date('2024-01-01');date.setDate(date.getDate() + 5); // mutation! date is now January 6// Better to create a new object:const newDate = new Date(date.getTime() + 5 * 24 * 60 * 60 * 1000);


Typing Unix Timestamps



Dates are often passed as numbers (milliseconds since 1970). Use a type alias for clarity:



type UnixTimestamp = number;

function formatTimestamp(ts: UnixTimestamp): string { return new Date(ts).toISOString();}

const myTimestamp: UnixTimestamp = 1705315200000;console.log(formatTimestamp(myTimestamp));


2. Formatting and Parsing Dates



Built-in Formatting Methods



JavaScript provides basic methods for localized output. In TypeScript, they work "out of the box":



const date = new Date('2024-06-15T14:30:00');

// Localized stringsconsole.log(date.toLocaleDateString('ru-RU')); // "15.06.2024"console.log(date.toLocaleTimeString('en-US')); // "2:30:00 PM"console.log(date.toLocaleString('de-DE')); // "15.6.2024, 14:30:00"

// ISO string (convenient for APIs)console.log(date.toISOString()); // "2024-06-15T11:30:00.000Z" (always UTC)


Parsing Strings: Dangers



Parsing strings via the new Date(str) constructor can yield unexpected results in different browsers. It is better to use Date.parse() with explicit validation or third-party libraries.



// Unreliable methodconst parsed = new Date('2024/01/15'); // may work inconsistently

// Reliable method: ISO 8601const safeParse = (dateStr: string): Date | null => { const ts = Date.parse(dateStr); return isNaN(ts) ? null : new Date(ts);};

const result = safeParse('2024-01-15T10:00:00Z');if (result) { console.log(result.toISOString());}


3. Advanced Manipulation and Comparison



Comparing Dates



Dates can be compared directly using comparison operators, but for exact comparison (equality), you need to convert to a number:



const date1 = new Date('2024-01-01');const date2 = new Date('2024-01-0                

Blogs

Book Recommendations