date-fns is a comprehensive, modular, and modern JavaScript utility library for working with dates. It provides a vast collection of functions for manipulating, formatting, parsing, and validating dates. Unlike some older date libraries, date-fns is built with a focus on immutability, pure functions, and modularity, making it highly efficient and easy to integrate into modern JavaScript projects, especially those using bundlers like Webpack or Rollup.
Key features and advantages of date-fns:
* Modularity: Each function is a standalone module, meaning you only import the specific functions you need. This leads to significantly smaller bundle sizes compared to importing entire libraries.
* Immutability: All date-fns functions return a new date instance rather than modifying the original date object. This prevents unintended side effects and makes your code more predictable and easier to debug.
* Pure Functions: Given the same input, a function will always return the same output, making them reliable and easy to test.
* Locale Support: It provides extensive localization capabilities, allowing you to format dates according to various cultural conventions and languages.
* TypeScript Friendly: Built with TypeScript in mind, it offers excellent type definitions out of the box, enhancing developer experience and catching potential errors during development.
* Browser & Node.js Compatible: It works seamlessly in both browser environments and Node.js applications.
* No Global Object Pollution: It does not extend native Date.prototype, avoiding potential conflicts with other libraries or your own code.
Common use cases for date-fns include:
* Formatting dates into human-readable strings (e.g., "MM/DD/YYYY", "October 26th, 2023").
* Parsing date strings into Date objects.
* Performing date arithmetic (adding/subtracting days, months, years, etc.).
* Comparing dates and calculating differences between them.
* Determining if a date is today, in the past, or in the future.
* Handling time zones and UTC conversions.
* Localizing date displays for different regions.
date-fns is often chosen over the native Date object due to the latter's limited functionality and sometimes cumbersome API, and over older libraries like Moment.js due to its modern design principles, smaller bundle size, and immutable nature.
Example Code
import React, { useState } from 'react';
import {
format,
parseISO,
addDays,
isToday,
differenceInDays,
formatDistanceToNow
} from 'date-fns';
import { enUS, tr } from 'date-fns/locale'; // Example locales
function DateFnsExample() {
const [currentDate, setCurrentDate] = useState(new Date());
const futureDateString = '2024-06-15T10:00:00Z'; // UTC time string
const futureDate = parseISO(futureDateString);
const fiveDaysLater = addDays(currentDate, 5);
return (
<div style={{ fontFamily: 'Arial, sans-serif', padding: '20px', maxWidth: '600px', margin: 'auto' }}>
<h1>date-fns Examples in React</h1>
<p><strong>Current Date:</strong> {format(currentDate, 'PPP')}</p>
<p>
<strong>Formatted Current Date (long):</strong>{' '}
{format(currentDate, 'EEEE, MMMM do, yyyy HH:mm:ss', { locale: enUS })}
</p>
<p>
<strong>Formatted Current Date (Turkish Locale):</strong>{' '}
{format(currentDate, 'EEEE, dd MMMM yyyy HH:mm:ss', { locale: tr })}
</p>
<h2>Parsing and Formatting Specific Dates</h2>
<p>
<strong>Original Future Date String:</strong> <code>{futureDateString}</code>
</p>
<p>
<strong>Parsed & Formatted Future Date:</strong>{' '}
{format(futureDate, 'MMM do, yyyy (hh:mm a)')}
</p>
<h2>Date Arithmetic</h2>
<p>
<strong>Current Date:</strong> {format(currentDate, 'PP')}
</p>
<p>
<strong>5 Days from now:</strong> {format(fiveDaysLater, 'PP')}
</p>
<h2>Date Comparisons & Differences</h2>
<p>
<strong>Is Today's Date 'today'?</strong>{' '}
{isToday(currentDate) ? 'Yes' : 'No'}
</p>
<p>
<strong>Days until Future Date:</strong>{' '}
{differenceInDays(futureDate, currentDate) > 0
? `${differenceInDays(futureDate, currentDate)} days left`
: 'Date has passed or is today'}
</p>
<h2>Relative Time</h2>
<p>
<strong>How long ago was the Future Date? (Relative to now):</strong>{' '}
{formatDistanceToNow(futureDate, { addSuffix: true })}
</p>
<button onClick={() => setCurrentDate(new Date())} style={{ marginTop: '20px', padding: '10px 15px' }}>
Refresh Current Date
</button>
<p style={{ marginTop: '20px', fontSize: '0.8em', color: '#666' }}>
<em>Note: Some advanced timezone operations might require the <code>date-fns-tz</code> package. This example focuses on core <code>date-fns</code> functionality.</em>
</p>
</div>
);
}
export default DateFnsExample;








date-fns