1. Accueil
  2. Articles
3 min de lecture
563 vues

How to Use Dates in JavaScript with the date-fns Library

Working with dates in JavaScript can be challenging due to its built-in Date object, which often lacks simplicity and intuitive methods. To simplify date manipulation and formatting, developers turn to libraries like date-fns. In this article, we'll explore how to use the date-fns library for working

Introduction to date-fns

date-fns is a lightweight , modular javascript library for date manipulation . Unlike moment.js , which bundles all its functionalities into a single package , date-fns provides modular functions , allowing you to import only what you need , thereby reducting bundle size.

Key Features :

  • Functional programming approach
  • Immutable and pure functions.
  • Modular imports to optimize performance.
  • Wide range of utility functions for date formatting , parsing , manipulation and comparisons.

Installing date-fns

To get started , you need to install the library , Use npm or yarn to add it to your project npm install date-fns or yarn add date-fns

Basic operations with date-fns

Formatting Dates

Formatting dates is one of the most common tasks in date handling , with date-fns , you can use the format function to convert a Date object into readable string.

1import { format } from 'date-fns';
2 
3const date = new Date(2025, 0, 8); // January 8, 2025
4const formattedDate = format(date, 'yyyy-MM-dd');
5 
6console.log(formattedDate); // Output: "2025-01-08"
1import { format } from 'date-fns';
2 
3const date = new Date(2025, 0, 8); // January 8, 2025
4const formattedDate = format(date, 'yyyy-MM-dd');
5 
6console.log(formattedDate); // Output: "2025-01-08"

The formatting tokens are intuitive and well documented . For example :

  • yyyy for the full year.
  • MM for the month.
  • dd for the day.
  • HH:mm:ss for time.

Parsing Dates

Parsing strings into date objects is equally simple , use the parse function to convert a string into date object based on a specific format :

1import { parse } from 'date-fns';
2 
3const dateString = '2025-01-08';
4const parsedDate = parse(dateString, 'yyyy-MM-dd', new Date());
5 
6console.log(parsedDate); // Output: Wed Jan 08 2025 00:00:00 GMT+0000 (UTC)
1import { parse } from 'date-fns';
2 
3const dateString = '2025-01-08';
4const parsedDate = parse(dateString, 'yyyy-MM-dd', new Date());
5 
6console.log(parsedDate); // Output: Wed Jan 08 2025 00:00:00 GMT+0000 (UTC)

Manipulating dates

You can manipulate dates with functions like Add , sub , set , and more . these functions return new Date objects without mutating the original date.

Adding Time :

1import { add } from 'date-fns';
2 
3const currentDate = new Date();
4const nextWeek = add(currentDate, { weeks: 1 });
5 
6console.log(nextWeek); // Output: Current date + 7 days
1import { add } from 'date-fns';
2 
3const currentDate = new Date();
4const nextWeek = add(currentDate, { weeks: 1 });
5 
6console.log(nextWeek); // Output: Current date + 7 days

Subtracting Time :

1import { sub } from 'date-fns';
2 
3const currentDate = new Date();
4const lastMonth = sub(currentDate, { months: 1 });
5 
6console.log(lastMonth); // Output: Current date - 1 month
1import { sub } from 'date-fns';
2 
3const currentDate = new Date();
4const lastMonth = sub(currentDate, { months: 1 });
5 
6console.log(lastMonth); // Output: Current date - 1 month

Common use case

Calculating date differences

To calculate the difference between two dates , you can use the differenceInDays , differnceInMonths or similar functions .

1import { differenceInDays } from 'date-fns';
2 
3const startDate = new Date(2025, 0, 1);
4const endDate = new Date(2025, 0, 8);
5 
6const daysDifference = differenceInDays(endDate, startDate);
7 
8console.log(daysDifference); // Output: 7
1import { differenceInDays } from 'date-fns';
2 
3const startDate = new Date(2025, 0, 1);
4const endDate = new Date(2025, 0, 8);
5 
6const daysDifference = differenceInDays(endDate, startDate);
7 
8console.log(daysDifference); // Output: 7

Comparing Date

You can compare two dates using functions like isBefore , isAfter , and isEqual .

1import { isBefore, isAfter } from 'date-fns';
2 
3const date1 = new Date(2025, 0, 1);
4const date2 = new Date(2025, 0, 8);
5 
6console.log(isBefore(date1, date2)); // Output: true
7console.log(isAfter(date1, date2)); // Output: false
1import { isBefore, isAfter } from 'date-fns';
2 
3const date1 = new Date(2025, 0, 1);
4const date2 = new Date(2025, 0, 8);
5 
6console.log(isBefore(date1, date2)); // Output: true
7console.log(isAfter(date1, date2)); // Output: false

Handling Time Zones

While date-fns itself doesn't include time zone support , you can use date-fns-tz , an extension of date-fns to handle time zones .

npm install date-fns-tz

Example :

1import { format, utcToZonedTime } from 'date-fns-tz';
2 
3const date = new Date('2025-01-08T10:00:00Z');
4const timeZone = 'America/New_York';
5 
6const zonedDate = utcToZonedTime(date, timeZone);
7const formattedDate = format(zonedDate, 'yyyy-MM-dd HH:mm:ssXXX', { timeZone });
8 
9console.log(formattedDate); // Output: "2025-01-08 05:00:00-05:00"
1import { format, utcToZonedTime } from 'date-fns-tz';
2 
3const date = new Date('2025-01-08T10:00:00Z');
4const timeZone = 'America/New_York';
5 
6const zonedDate = utcToZonedTime(date, timeZone);
7const formattedDate = format(zonedDate, 'yyyy-MM-dd HH:mm:ssXXX', { timeZone });
8 
9console.log(formattedDate); // Output: "2025-01-08 05:00:00-05:00"

Conclusion

The date-fns library is a powerful tool for handling dates in JavaScript. It simplifies common tasks like formatting, parsing, and manipulating dates, all while keeping your code clean and efficient. Its modular approach ensures you only include what you need, making it a lightweight and performance-friendly solution.

If you're working on projects that involve heavy date operations, integrating date-fns into your workflow can save you time and reduce complexity.