Working with Dates and Time in TypeScript: A Complete Guide

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

Working with Dates and Time in TypeScript: From Basics to Advanced Techniques



Managing dates and time is one of the key tasks in web development. Whether it's displaying publication time, calculating deadlines, or synchronizing data with a server, TypeScript provides powerful tools for working with timestamps. In this article, we will cover all aspects of working with dates: from creating a Date object to complex timezone manipulations and formatting.



1. Basics of Working with the Date Object in TypeScript



In TypeScript, as in JavaScript, the built-in Date object is responsible for working with dates. Thanks to strict typing, TypeScript helps avoid errors when passing incorrect data.



Creating a Date Object

There are several ways to create a date instance:



// Current date and timeconst now: Date = new Date();console.log(now); // Tue Oct 24 2023 14:30:00 GMT+0300

// By milliseconds (Unix timestamp)const fromTimestamp: Date = new Date(1698153000000);

// From a string (ISO 8601)const fromString: Date = new Date("2023-10-24T12:00:00Z");

// From components (year, month, day, hours, minutes, seconds)const customDate: Date = new Date(2023, 9, 24, 14, 30, 0); // Months are 0-indexed!


Important: Months in JavaScript/TypeScript are numbered from 0 (January — 0, December — 11). This is a common source of bugs.



Getting Date Components

Getters are used to extract individual parts of a date:



const date: Date = new Date();const year: number = date.getFullYear();      // 2023const month: number = date.getMonth();         // 9 (October)const day: number = date.getDate();            // 24const hours: number = date.getHours();         // 14const minutes: number = date.getMinutes();     // 30const seconds: number = date.getSeconds();     // 0const dayOfWeek: number = date.getDay();       // 2 (Tuesday, 0 - Sunday)


2. Formatting and Displaying Dates



The standard Date.toString() output is often unsuitable for user interfaces. Let's look at the main formatting methods.



Built-in Formatting Methods

  • toDateString() — "Tue Oct 24 2023"
  • toLocaleDateString() — localized date (e.g., "10/24/2023" for US)
  • toISOString() — string in ISO format ("2023-10-24T11:30:00.000Z")


const date: Date = new Date();console.log(date.toLocaleDateString('en-US')); // 10/24/2023console.log(date.toLocaleTimeString('en-US')); // 2:30:00 PM


Custom Formatting with Intl.DateTimeFormat

For more flexible control, use Intl.DateTimeFormat:



const date: Date = new Date();const formatter = new Intl.DateTimeFormat('en-US', {    year: 'numeric',    month: 'long',    day: 'numeric',    weekday: 'long',    hour: '2-digit',    minute: '2-digit'});console.log(formatter.format(date)); // "Tuesday, October 24, 2023, 02:30 PM"


The date-fns Library

For complex tasks, it is recommended to use the date-fns library. It is lightweight and has excellent TypeScript support:



import { format, addDays, isWeekend } from 'date-fns';import { enUS } from 'date-fns/locale';

const date: Date = new Date();console.log(format(date, 'MM/dd/yyyy', { locale: enUS })); // "10/24/2023"console.log(format(date, 'HH:mm:ss')); // "14:30:00"console.log(isWeekend(date)); // false


3. Date Manipulations: Addition, Subtraction, and Comparison



Modifying a Date

The simplest way is to use setters:



const date: Date = new Date();date.setFullYear(2024);date.setMonth(11); // Decemberdate.setDate(31);console.log(date); // "Tue Dec 31 2024 14:30                

Blogs

Book Recommendations