Introduction: Why is the Standard Date() Not Enough?
The built-in Date object in JavaScript is a powerful but not always convenient tool. When developing complex applications on Node.js (for example, task schedulers, analytics systems, or financial services), developers encounter a number of problems:
- Mutability: methods like
setMonth()modify the original object. - Limited time zone support:
Dateonly works with local time and UTC. - Complexity of formatting: there is no built-in analog of
strftime. - String parsing:
new Date("2023-13-01")will not throw an error, but will create "2024-01-01".
In this article, we will look at advanced approaches to working with dates and time in Node.js that will help avoid these problems and write more reliable code.
1. Intl.DateTimeFormat: Formatting Without External Dependencies
Modern JavaScript (ES6+) provides a built-in internationalization API Intl.DateTimeFormat. This is a powerful tool that allows you to format dates and time for any locale without connecting third-party libraries.
Basic Usage
const date = new Date('2024-03-15T14:30:00Z');
// Formatting for Russian localeconst formatterRU = new Intl.DateTimeFormat('ru-RU', { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long', hour: '2-digit', minute: '2-digit'});
console.log(formatterRU.format(date));// "пятница, 15 марта 2024 г., 17:30"Advanced Options: Time Zones and Relative Time
// Formatting with time zone considerationconst formatterTZ = new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York', dateStyle: 'full', timeStyle: 'short'});console.log(formatterTZ.format(date));// "Friday, March 15, 2024 at 10:30 AM"
// Relative formatting (Intl.RelativeTimeFormat)const rtf = new Intl.RelativeTimeFormat('ru', { numeric: 'auto' });console.log(rtf.format(-5, 'day')); // "5 дней назад"console.log(rtf.format(2, 'month')); // "через 2 месяца"This approach is ideal when you need to avoid unnecessary dependencies but require flexible formatting for the user interface.
2. The date-fns Library: Modularity and Functionality
date-fns is a modern library built on the principles of functional programming. Its main advantage is modularity: you import only the functions you need, which significantly reduces the bundle size.
Installation and Basic Examples
// Installation: npm install date-fnsimport { format, addDays, subMonths, differenceInDays, isWeekend } from 'date-fns';import { ru } from 'date-fns/locale';
const today = new Date();
// Formatting with localeconsole.log(format(today, 'dd MMMM yyyy, EEEE', { locale: ru }));// "15 марта 2024, пятница"
// Date arithmeticconst nextWeek = addDays(today, 7);const lastMonth = subMonths(today, 1);
// Difference between datesconst diff = differenceInDays(nextWeek, today);console.log(diff); // 7
// Weekend checkconsole.log(isWeekend(today)); // true or falseComplex Scenarios: Comparison and Validation
import { parse, isValid, isBefore, isAfter, startOfMonth, endOfMonth } from 'date-fns';
// Safe parsingconst parsed = parse('2024-13-01', 'yyyy-MM-dd', new Date());console.log(isValid(parsed)); // false — invalid date
// Working with rangesconst start = startOfMonth(new Date(2024, 2, 1)); // March 1const end = endOfMonth(new Date(2024, 2, 1)); // March 31
const targetDate = new Date(2024, 2, 15);if (isAfter(targetDate, start) && isBefore(targetDate, end)) { console.log('The date is in March 2024');}date-fns