Working with Dates Using date-fns in JavaScript.

Working with dates is not an easy task. But the date-fns package makes it easy to work with dates in JavaScript.

Let’s dig into the date-fns package to make our lives easier than before. The date-fns package is lightweight.

Working with Dates Using date-fns in JavaScript

Installing the package

We need to configure the project with npm to work with a third party package. Let’s quickly walk through the steps to complete our setup.

I assume you have NodeJS or IDE installed to practice this.

Working with Dates Using date-fns in JavaScript
  • Navigate to the desired directory that you want to work in.
  • Run the npm init command to initialize the project.
  • Please answer all questions according to your preference.
  • Now, install date-fns using the following command

npm install date-fns

  • Create a file called dateFunctions.js

Now, we’re ready to jump into the date-fns package. Let’s go and learn some essential methods of the package.

Working with Dates Using date-fns in JavaScript

It is valid

All dates are invalid.

For example, there is no date like 2021-02-30. How can we check whether the date is valid or not?

Working with Dates Using date-fns in JavaScript

The isValid from the date-fns method in the package will help us find out if the given date is valid or not.

Examine whether or not the following code works well with valid dates.

const { isValid } = require(“date-fns”); console.log(isValid(new Date(“2021, 02, 30”)));

Working with Dates Using date-fns in JavaScript

If you run the code above, you’ll find that February 30, 2021 is valid. Oh! It is not.

Why is it happening?

JavaScript converts the extra day in February to March 1, 2021, which is a valid date. To confirm this, print a new Date (“2021, 02, 30”) to the console.

Working with Dates Using date-fns in JavaScript

console.log(new Date(“2021, 02, 30”));

The date-fns package provides a method called parse to work around this problem. The parse method parses the date you provided and returns accurate results.

Take a look at the following code.

const { isValid, parse } = require(“date-fns”); const invalidDate = parse(“30.02.2021”, “dd.MM.yyyy”, new Date()); const validDate = parse(“25.03.2021”, “dd.MM.yyyy”, new Date()); console.log(isValid(invalidDate)); console.log(isValid(validDate));

Working with Dates Using date-fns in JavaScript

Format

One of the basic uses when working with dates is to format them as we want. We format dates in different formats using the format method of the date-fns package.

Format the date as 01-23-1993, 1993-01-23 10:43:55, Tuesday, Jan 23, 1993, etc. Run the following code to get the corresponding date in the mentioned formats.

const { format } = require(“date-fns”); console.log(format(new Date(), “dd-MM-yyyy”)); console.log(format(new Date(), “mm/dd/yyyy HH:mm:ss”)); console.log(format(new Date(), “PPPP”));

Working with Dates Using date-fns in JavaScript

You can find the full list of formats.

add days

The addDays method is used to set a deadline after a certain number of days.

We can simply add days to any date to get the date of the day after some days. It has many applications.

Let’s say you have a birthday after X days and you are busy on those days. You may not remember the birthday in your busy schedule. You can simply use the addDays method to notify you of the birthday after X days. Have the code.

const { format, addDays } = require(“date-fns”); const today = new Date(); // birthday after 6 days const birthday = addDays(today, 6); console.log(format(today, “PPPP”)); console.log(format(birthday, “PPPP”));

Like the addDays method, there are other methods like addHours, subHours, addMinutes, subMinutes, addSeconds, subSeconds, subDays, addWeeks, subWeeks, addYears, subYears, etc. You can easily guess the functionality of the methods from their names.

try them.

formatDistance

Writing code to compare dates from scratch is a nightmare. Why do we compare dates anyway?

Working with Dates Using date-fns in JavaScript

There are many apps where you have seen date comparisons. If you take social media websites, there will be a catchphrase that you mention 1 minute ago, 12 hours ago, 1 day ago, etc. Here, we use date comparison from the publication date and time to the current date and time.

The formatDistance method does the same. Returns the gap between the two given dates.

Let’s write a program to find your age.

const { formatDistance } = require(“date-fns”); const birthday = new Date(“1956, 01, 28”); const presentDay = new Date(); console.log(`Age: ${formatDistance(presentDay, birthday)}`);

Working with Dates Using date-fns in JavaScript

everyDayOfInterval

Let’s say you have to find the names and dates of the next X days. The eachDayOfInterval method helps us find the days between the start and end date.

Let’s find out the next 30 days from today.

const { addDays, eachDayOfInterval, format } = require(“date-fns”); const presentDay = new Date(); const after30Days = addDays(presentDay, 30); const _30Days = eachDayOfInterval({ start: presentDay, end: after30Days }); _30Days.forEach((day) => { console.log(format(day, “PPPP”)); });

maximum and minimum

The max and min methods find the maximum and minimum dates between the given dates respectively. The methods in date-fns are very familiar and easy to guess the functionality of those methods. Let’s write some code.

const { min, max } = require(“date-fns”); const _1 = new Date(“1990, 04, 22”); const _2 = new Date(“1990, 04, 23”); const _3 = new Date(“1990, 04, 24”); const _4 = new Date(“1990, 04, 25”); console.log(`Max: ${max([_1, _2, _3, _4])}`); console.log(`Min: ${min([_1, _2, _3, _4])}`);

It does not matter

You can easily guess the functionality of the isEqual method. As you think, the isEqual method is used to check if two dates are equal or not. See the sample code below.

const { isEqual } = require(“date-fns”); const _1 = new Date(); const _2 = new Date(); const _3 = new Date(“1900, 03, 22”); console.log(isEqual(_1, _2)); console.log(isEqual(_2, _3)); console.log(isEqual(_3, _1));

conclusion

If we talk about all the methods in the date-fns package, it takes days to complete. The best way to learn any package is to become familiar with the core methods of the package, and then read the documentation for more information. Apply the same scenario for the date-fns package as well.

You have learned the essential methods in this tutorial. Look up the specific usage in the or consider taking online courses like .

Happy coding 👨‍💻