date-fns: Parsing and Formatting
You'll learn how to use date-fns's parse() and format() functions to confidently convert between date strings and Date objects using explicit patterns.
Why Explicit Patterns Matter
Native JavaScript's Date parsing is notoriously inconsistent across browsers. date-fns solves this by requiring you to specify exactly what format your date string uses. Think of it like a translation dictionary: you tell date-fns "this date is written in French format," and it knows precisely how to read it—no guessing games.
Formatting Dates with format()
The format() function converts a Date object into a string using a pattern you define:
import { format } from 'date-fns';
const now = new Date(2024, 5, 15, 14, 30); // June 15, 2024, 2:30 PM
format(now, 'yyyy-MM-dd'); // "2024-06-15"
format(now, 'MMM do, yyyy'); // "Jun 15th, 2024"
format(now, 'EEEE, MMMM d'); // "Saturday, June 15"
format(now, 'h:mm a'); // "2:30 PM"
format(now, 'yyyy-MM-dd HH:mm:ss'); // "2024-06-15 14:30:00"
Each letter in the pattern represents a date/time unit: yyyy = four-digit year, MM = two-digit month, dd = two-digit day, etc.
Parsing Strings with parse()
The parse() function works in reverse—it reads a date string using your specified pattern and returns a Date object:
import { parse } from 'date-fns';
const referenceDate = new Date(); // Required for ambiguous dates
const date1 = parse('2024-06-15', 'yyyy-MM-dd', referenceDate);
const date2 = parse('Jun 15th, 2024', 'MMM do, yyyy', referenceDate);
const date3 = parse('15/06/2024 14:30', 'dd/MM/yyyy HH:mm', referenceDate);
The third argument (reference date) fills in missing information when your pattern doesn't specify everything (like time of day).
Key Takeaway: date-fns format() and parse() eliminate ambiguity by requiring explicit pattern strings, giving you complete control over how dates are displayed and interpreted across all browsers.