Working with Dates and Time in TypeScript: From Basics to Advanced Techniques
Working with dates and time is one of the most common tasks in web development. TypeScript, being a superset of JavaScript, inherits the built-in Date object but adds strict typing to it. In this article, we will break down how to work effectively with dates in TypeScript: from creation and formatting to complex timezone manipulations. You will learn how to avoid typical mistakes and make your code more reliable and readable.
Basics: Creating and Basic Operations with Dates
The Date object in TypeScript is the same JavaScript object, but with improved type support. Let's look at the main ways to create dates:
// Current date and timeconst now: Date = new Date();
// From a string (ISO 8601)const specificDate: Date = new Date('2024-12-25T10:30:00Z');
// From components (year, month (0-11), day, hours, minutes, seconds)const customDate: Date = new Date(2024, 11, 25, 10, 30, 0); // December 25, 2024
// From milliseconds (Unix timestamp)const fromTimestamp: Date = new Date(1703493000000);It is important to remember that months in JavaScript/TypeScript are numbered from 0 (January — 0, December — 11). This is a common source of errors for beginners. To avoid confusion, it is recommended to use string formats or libraries.
Basic methods for getting date components:
getFullYear()— returns the year (4 digits)getMonth()— month (0-11)getDate()— day of the month (1-31)getDay()— day of the week (0 — Sunday, 6 — Saturday)getHours(),getMinutes(),getSeconds()— timegetTime()— number of milliseconds since January 1, 1970
Example of usage with typing:
function formatDate(date: Date): string { const year: number = date.getFullYear(); const month: string = String(date.getMonth() + 1).padStart(2, '0'); const day: string = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`;}
const today: Date = new Date();console.log(formatDate(today)); // "2024-12-25"Formatting and Displaying Dates
Built-in date formatting methods in TypeScript are limited. For simple tasks, you can use toLocaleDateString() and toLocaleTimeString():
const date: Date = new Date('2024-12-25T10:30:00');
// Localized formatconsole.log(date.toLocaleDateString('ru-RU')); // "25.12.2024"console.log(date.toLocaleTimeString('ru-RU')); // "10:30:00"
// Full formatconsole.log(date.toLocaleString('ru-RU', { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long'})); // "среда, 25 декабря 2024 г."However, for complex formatting or strict control over the output, it is better to use specialized libraries. The most popular one is date-fns — lightweight, modular, and fully compatible with TypeScript.
Installation:
npm install date-fnsExample of usage:
import { format, addDays, parseISO } from 'date-fns';import { ru } from 'date-fns/locale';
const date: Date = parseISO('2024-12-25T10:30:00');
// Formattingconsole.log(format(date, 'dd.MM.yyyy')); // "25.12.2024"console.log(format(date, 'PPP', { locale: ru })); // "25 декабря 2024 г."
// Adding daysconst futureDate: Date = addDays(date, 10);console.log(format(futureDate, 'dd.MM.yyyy')); // "04.01.2025"Other useful functions from date-fns: differenceInDays, isBefore, isAfter, startOfMonth, endOfWeek and many others. The library allows you to write clean, functional code without mutating the original