date-fns is a modern, comprehensive JavaScript utility library designed for manipulating dates in both browser and Node.js environments. The current stable version is 4.1.0. It distinguishes itself by exclusively using native JavaScript `Date` objects, thereby avoiding global object extension, and promoting immutability through its pure functions that consistently return new date instances. The library offers over 200 functions, is highly modular, supports tree-shaking for optimized bundle sizes, and provides first-class TypeScript support with meticulously crafted types. It maintains a consistent and relatively fast release cadence, with major versions v3 and v4 released less than a year apart, aiming to minimize breaking changes in future releases. Additionally, date-fns boasts extensive internationalization capabilities with dozens of available locales.
npm install date-fnsVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates basic date formatting, sorting with `compareAsc`, adding days with `addDays`, and using `formatInTimeZone` from `date-fns-tz` for time zone conversion.
Review TypeScript usage and adapt to updated internal types if directly referencing them. Ensure `date-fns-tz` is installed and updated for time zone functionality.
Install `date-fns-tz` (e.g., `npm install date-fns-tz`) and ensure it's at least v1.0.2. Import functions like `formatInTimeZone` from `date-fns-tz`.
Always use `yyyy` for year and `dd` for day of month. Consult the documentation for specific token usage and required options, especially for less common formats.
While this fixes unexpected crashes, ensure your code handles `Invalid Date` or `NaN` outputs for potentially malformed date inputs, rather than relying on an exception being thrown for `null`.
Upgrade to the latest stable version (4.x or higher) to benefit from these crucial bug fixes. If remaining on 3.x, ensure you are on at least v3.3.1.
For ESM, use `import { functionName } from 'date-fns'`. For CommonJS in older Node.js or build setups, use `const { functionName } = require('date-fns')` or `const functionName = require('date-fns/functionName')` (preferred for tree-shaking).When creating a new `Date` object with `new Date(year, monthIndex, day)`, remember to subtract 1 from the conventional month number (e.g., `new Date(2024, 0, 1)` for January 1, 2024).
Import the desired locale (e.g., `import { enUS } from 'date-fns/locale'`) and pass it to the function via its options object: `format(date, 'PPP', { locale: enUS })`.First, ensure `date-fns-tz` is installed (`npm install date-fns-tz`). Then, verify the import statement: `import { formatInTimeZone } from 'date-fns-tz'`. Do not import time zone functions directly from `date-fns`.