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.
import { format } from 'date-fns'; const date = new Date(2025, 0, 8); // January 8, 2025const formattedDate = format(date, 'yyyy-MM-dd'); console.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 :
import { parse } from 'date-fns'; const dateString = '2025-01-08';const parsedDate = parse(dateString, 'yyyy-MM-dd', new Date()); console.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 :
import { add } from 'date-fns'; const currentDate = new Date();const nextWeek = add(currentDate, { weeks: 1 }); console.log(nextWeek); // Output: Current date + 7 days
Subtracting Time :
import { sub } from 'date-fns'; const currentDate = new Date();const lastMonth = sub(currentDate, { months: 1 }); console.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 .
import { differenceInDays } from 'date-fns'; const startDate = new Date(2025, 0, 1);const endDate = new Date(2025, 0, 8); const daysDifference = differenceInDays(endDate, startDate); console.log(daysDifference); // Output: 7
Comparing Date
You can compare two dates using functions like isBefore , isAfter , and isEqual .
import { isBefore, isAfter } from 'date-fns'; const date1 = new Date(2025, 0, 1);const date2 = new Date(2025, 0, 8); console.log(isBefore(date1, date2)); // Output: trueconsole.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 :
import { format, utcToZonedTime } from 'date-fns-tz'; const date = new Date('2025-01-08T10:00:00Z');const timeZone = 'America/New_York'; const zonedDate = utcToZonedTime(date, timeZone);const formattedDate = format(zonedDate, 'yyyy-MM-dd HH:mm:ssXXX', { timeZone }); console.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.