• Get application security done the right way! Detect, Protect, Monitor, Accelerate, and more…
  • Working with dates is not an easy task. But, the package date-fns makes it easy to work with the dates in JavaScript.

    Let’s deep dive into the package date-fns to makes our lives easier than before. The package date-fns is lightweight.

    Installing the package

    We need to set up the project with the npm to work with a third-party package. Let’s quickly see the steps to complete our setup.

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

    • Navigate to the desired directory that you want to work in.
    • Run the command npm init to initialize the project.
    • Answer all the questions based on your preference.
    • Now, install the date-fns using the below command
    npm install date-fns
    • Create a file called dateFunctions.js

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

    isValid

    All dates are not valid.

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

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

    Examine whether the following code works fine or not with the validity of the dates.

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

    If you execute the above code, then you will find 30th February 2021 is valid. Oh! It’s not.

    Why is it happening?

    JavaScript converts the extra day of February to 1st March 2021 which is a valid date. To confirm it, print new Date("2021, 02, 30") to the console.

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

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

    Have a look at the below 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));
    

    format

    One of the basic usage while working with dates is formating them as we want. We format the dates in different formats using the format method from the date-fns package.

    Format the date as 23-01-1993, 1993-01-23 10:43:55, Tuesday, January 23rd 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(), "dd/MM/yyyy HH:mm:ss"));
    console.log(format(new Date(), "PPPP"));
    

    You can find the complete list of formats here.

    addDays

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

    Simply, we can 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 make use of the addDays method to notify you about 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"));
    

    Similar to the method addDays 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 with their names.

    Try them out.

    formatDistance

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

    There are many applications where you have seen date comparisons. If you take social media websites, there will a tagline mentioning 1 minute ago, 12 hours ago, 1 day ago, etc.., Here, we use date comparison from the post date and time to present date and time.

    The method formatDistance does the same thing. It returns the gap between the given two 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)}`);
    

    eachDayOfInterval

    Let’s say you have to find about the next X days names and dates. The method eachDayOfInterval helps us to 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"));
    });
    

    max and min

    The methods max and min finds the maximum and minimum dates among the given dates respectively. The methods in the 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])}`);

    isEqual

    You can easily guess the functionality of the method isEqual. As you think the method isEqual is used to check whether 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 every method in the date-fns package, then it takes days to complete. The best way to learn any package is to get familiar with the essential methods from it and then reading the documentation for further information. Apply the same scenario for the date-fns package as well.

    You have learned the essential methods in this tutorial. Search the specific usage in the documentation or consider taking online courses such as JavaScript, jQuery, and JSON.

    Happy Coding 👨‍💻