Advanced Date and Time Handling in TypeScript
Working with dates and time is one of the most common yet complex tasks in web development. In TypeScript, thanks to strict typing, we can avoid many errors related to date manipulation, but the standard Date object has several limitations. In this article, we will explore advanced approaches to working with dates and time, including the use of modern libraries, typing, time zone handling, and parsing complex formats.
1. Problems with Native Date and Their Solution Using TypeScript
The standard Date in JavaScript is extremely inconvenient for complex operations:
- Mutability: methods like
setDate()modify the original object. - Lack of formatting: there is no built-in way to output a date in the "DD.MM.YYYY" format.
- Poor time zone support:
Datestores time in UTC, whilegetHours()methods return local time. - Parsing issues:
new Date("2023-01-01")can be interpreted differently in different browsers.
TypeScript helps by allowing us to create wrappers and utilities. For example, we can define strict types for formatting:
type DateFormat = 'DD.MM.YYYY' | 'YYYY-MM-DD' | 'HH:mm:ss';
function formatDate(date: Date, format: DateFormat): string { const day = String(date.getDate()).padStart(2, '0'); const month = String(date.getMonth() + 1).padStart(2, '0'); const year = date.getFullYear(); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); const seconds = String(date.getSeconds()).padStart(2, '0');
switch (format) { case 'DD.MM.YYYY': return `${day}.${month}.${year}`; case 'YYYY-MM-DD': return `${year}-${month}-${day}`; case 'HH:mm:ss': return `${hours}:${minutes}:${seconds}`; default: return ''; }}
// Usageconst now = new Date();console.log(formatDate(now, 'DD.MM.YYYY')); // "15.10.2023"This approach ensures that we do not pass an invalid format to the function, as TypeScript will check the type at compile time.
2. Using the date-fns Library: Purity and Functionality
date-fns is a modern library for working with dates that is perfectly suited for TypeScript. Its main advantages are:
- Immutability: all functions return new objects without modifying the original ones.
- Modularity: you import only the functions you need, which reduces bundle size.
- Typing: the library has built-in TypeScript support.
Installation:
npm install date-fnsExamples of advanced usage:
import { format, addDays, differenceInDays, isWeekend, parseISO } from 'date-fns';
// Formattingconst date = new Date(2023, 9, 15); // October 15, 2023console.log(format(date, 'dd.MM.yyyy')); // "15.10.2023"console.log(format(date, 'EEEE, MMMM do yyyy')); // "Sunday, October 15th 2023"
// Arithmeticconst nextWeek = addDays(date, 7);console.log(format(nextWeek, 'dd.MM.yyyy')); // "22.10.2023"
// Difference between datesconst startDate = new Date(2023, 0, 1);const endDate = new Date(2023, 11, 31);const diff = differenceInDays(endDate, startDate);console.log(diff); // 364
// Weekend checkconsole.log(isWeekend(date)); // true (Sunday)
// Parsing ISO stringconst parsed = parseISO("2023-10-15T10:30:00Z");console.log(format(parsed, 'HH:mm')); // "13:30" (considering time zone)Important: date-fns works with Date objects, so