Utilising date-fns Library (Version 3)
Introduction
In this lesson, we will explore the date-fns
library, focusing on its version 3. This library is a modern JavaScript tool that provides a comprehensive yet straightforward set of functions for manipulating, formatting, and working with dates. Unlike other date libraries, date-fns
offers a modular approach, allowing developers to include only the functions they need, which results in smaller bundle sizes for web applications.
Objectives
- Understand the basic usage of the
date-fns
library. - Learn to manipulate and format dates using
date-fns
. - Implement practical examples demonstrating the library’s capabilities.
Body
1. Introduction to date-fns
date-fns is a lightweight, easy-to-use library for date manipulation. Its functional programming approach allows for elegant and concise code. Version 3 of date-fns
includes various enhancements and optimizations over its predecessors.
2. Setting Up date-fns
To use date-fns
in your project, you first need to install it:
npm install date-fns@3
3. Basic Date Operations
a. Formatting Dates
import { format } from 'date-fns';
const now = new Date();
console.log(format(now, 'dd/MM/yyyy')); // e.g., "28/01/2024"
Description: This example shows how to format the current date in a dd/MM/yyyy
format, a common requirement in web applications.
b. Adding Time
import { addDays } from 'date-fns';
const tomorrow = addDays(new Date(), 1);
console.log(format(tomorrow, 'dd/MM/yyyy')); // e.g., "29/01/2024"
Description: Here, we add one day to the current date. This function is particularly useful for calculating deadlines or future events.
4. Comparing Dates
import { isBefore, isAfter } from 'date-fns';
const date1 = new Date(2024, 0, 28); // 28 January 2024
const date2 = new Date(2024, 0, 29); // 29 January 2024
console.log(isBefore(date1, date2)); // true
console.log(isAfter(date1, date2)); // false
Description: This snippet demonstrates how to compare dates to check which one is earlier or later.
Task
Create a function using date-fns
that takes two dates as arguments and returns the number of days between them. Remember to handle the scenario where the second date is earlier than the first.
Solution
Below is a JavaScript function that uses the date-fns
library to calculate the number of days between two dates.
NOTE: In the example below, we’ve used JSDocs to document the function. We will cover JSDocs in more detail in a later lesson. For now, you can ignore the JSDocs and focus on the code. It’s added to make the code more readable and understandable.
import { differenceInDays } from 'date-fns';
/**
* Calculates the number of days between two dates.
*
* @param {Date} date1 - The start date.
* @param {Date} date2 - The end date.
* @return {number} The number of days between the two dates.
*/
function daysBetweenDates(date1, date2) {
// Use the differenceInDays function from date-fns to calculate the difference.
// The function automatically handles the scenario where date2 is earlier than date1.
return Math.abs(differenceInDays(date1, date2));
}
// Example Usage:
const start = new Date(2024, 0, 28); // 28 January 2024
const end = new Date(2024, 1, 3); // 3 February 2024
console.log(daysBetweenDates(start, end)); // Outputs the number of days between the dates
Explanation of the Code
Importing from date-fns: The function
differenceInDays
is imported from thedate-fns
library. This function is used to calculate the difference in days between two dates.Function Declaration:
daysBetweenDates
is a function that takes twoDate
objects (date1
anddate2
) as parameters.Calculating the Difference: Inside the function,
differenceInDays
is called withdate1
anddate2
as arguments. This function returns the difference in days between the two dates. It accounts for whetherdate2
is before or afterdate1
.Returning the Absolute Value:
Math.abs
is used to ensure the function returns a positive number, representing the absolute number of days between the dates, regardless of their order.Example Usage: The function is then demonstrated with an example, using two dates, and the result is logged to the console.