Go Back

2 min read

Formatting Dates with date-fns in React

profile

Nitin k

|

November 25, 2024

views

Formatting dates is a crucial aspect of building user-friendly applications. In this blog, we’ll explore how to use date-fns, a popular JavaScript library, to format dates and calculate relative time.

Example: Date Formatting Function

Here’s a handy function that formats dates using date-fns:

React Snippet

formatDate.ts

How It Works:

  • Full Date: Displays a complete formatted date.
  • Relative Time: Shows how long ago the date occurred.
  • Only Date: Provides a clean date format.

Why Use date-fns?

  • Lightweight: date-fns is modular, letting you import only what you need.
  • Comprehensive: It supports a wide range of date operations.
  • Immutable: Functions don't mutate the original date.

Example Usage

index.tsx

Conclusion

Using date-fns simplifies date formatting and calculations in React projects. Its modular design and comprehensive functionality make it a go-to solution for date management.