Working with Dates and Time in JavaScript: From A to Z for Node.js

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 JavaScript is a Challenge for Developers

Working with dates and time is one of the most common and simultaneously tricky tasks in web development. It seems like what could be simpler than getting the current date or calculating the difference between two events? However, in practice, JavaScript (Node.js) developers encounter many pitfalls: time zones, ISO format, the non-obvious behavior of the getMonth() method, and outdated libraries. In this article, we will break down working with dates from basic principles to advanced techniques, using only the standard Date object and the modern date-fns library.



1. Basics of the Date Object in Node.js

The built-in Date object is the foundation for working with time. It stores the number of milliseconds that have passed since January 1, 1970 (Unix epoch). Let's look at the basic operations.



Creating and Getting the Current Time

The simplest way to create a date object is to call new Date() without arguments. This returns the current date and time on the server.

// Current date and time (in the server's time zone)const now = new Date();console.log(now); // Example: 2024-05-20T14:30:00.000Z

// Creating from an ISO stringconst specificDate = new Date('2024-12-25T10:00:00');console.log(specificDate); // 2024-12-25T10:00:00.000Z

// Creating from components (year, month, day, hours, minutes, seconds)const birthday = new Date(1990, 5, 15); // Note: month 5 = June!console.log(birthday); // 1990-06-15T00:00:00.000Z

Important note: Months in JavaScript are zero-indexed (January is 0, December is 11). This is a common source of bugs.



Methods for Getting Date Components

Getters are used to extract individual parts of a date. Remember that they return values in the server's local time zone.

const date = new Date('2024-03-15T12:30:45');

console.log(date.getFullYear()); // 2024console.log(date.getMonth()); // 2 (March, since the count starts from 0)console.log(date.getDate()); // 15console.log(date.getDay()); // 5 (Friday, 0 - Sunday)console.log(date.getHours()); // 12console.log(date.getMinutes()); // 30console.log(date.getSeconds()); // 45

For working in UTC (Coordinated Universal Time), use methods with the getUTC... prefix, for example getUTCHours().



2. Formatting and Displaying Dates

Node.js does not have a built-in convenient way to format dates into an arbitrary string format (e.g., "March 15, 2024"). There are two ways to do this: manual string construction or using libraries.



Manual Formatting (without third-party libraries)

If you need to output a date in a simple format, you can write a small function.

function formatDate(date) {  const day = String(date.getDate()).padStart(2, '0');  const month = String(date.getMonth() + 1).padStart(2, '0');  const year = date.getFullYear();  return `${day}.${month}.${year}`;}

const today = new Date();console.log(formatDate(today)); // Example: "20.05.2024"


Modern Solution: The date-fns Library

The date-fns library is a modern, modular, and lightweight alternative to the outdated moment.js. It is ideal for Node.js.

// Installation: npm install date-fns

const { format, addDays, differenceInDays } = require('date-fns');const { ru } = require('date-fns/locale'); // Localization

const date = new Date();

// Formatting with localizationconsole.log(format(date, 'dd MMMM yyyy', { locale: ru }));// Example: "20 мая 2024"

// Adding daysconst nextWeek = addDays(date, 7);console.log(format(nextWeek, 'yyyy-MM-dd')); // "2024-05-27"

// Difference in daysconst start = new Date(2024, 0, 1);const end = new Date(2024, 11, 31);co

Blogs

Book Recommendations