Node.js date-fns: Good date handling in JavaScript

Working with dates is a problem of the first hour of the language. Although JavaScript basically has a Date object that you can theoretically use to perform date calculations, there are not many weaknesses in the API. Fortunately, there are helpful libraries like Node.js date-fns that can save us a lot of work.

For example, one problem is how to deal with different time zones in the date objects, so JavaScript uses the current time zone of the system as a basis. Especially with cross-time applications, this can lead to difficulties. Another peculiarity of the Date object in JavaScript is the representation of the month. For example, January is given the value 0. However, if the daily and year numbers are JavaScript again, then the 5th standard of a month is represented by the number 5.

When implementing an application that uses dates, you often encounter the task of creating, modifying, and outputting them. The creation and output is possible without any problems with the on-board tools of JavaScript. If, however, you want to modify a date, for example, if you want to subtract two days from a date, this is no longer possible without further ado. Of course, you can get the timestamp of the date and then subtract the appropriate number of milliseconds to get to the target date. However, this approach is not easy to read and easy to maintain or even very elegant. For this reason, and for a number of other reasons, many libraries have evolved in the past to help you use date values ​​in JavaScript. One of the most widely used solutions in the market is Moment.js. However, the top dog got a serious competitor some time ago: the project date-fns.

How is Node.js date-fns different from Moment.js?

The first and one of the most important differences is already in the name of the project, because fns stands for Functions. Node.js date-fns is a collection of functions that you can use to work with dates. In contrast, Moment.js takes an object-oriented approach. Here you create a moment instance and work with the methods of this object. This of course affects the package size. By default, Moment.js includes the entire interface. Although you can optimize the package, additional steps are required. With date-fns you only load the functions that you really need. In a backend application with Node.js this consideration does not play too much, as the package size is rather minor. You can also use date-fns as well as Moment.js in the frontend in your browser. Here the package size is crucial.

The developers of Node.js date-fns have not only paid attention to subdividing the project into many small and largely independent functions, but also that the functions are pure functions. For example, you pass the addHours function a date object and the number of hours to add. The result is a new date object, with the specified number of hours later than when typing. So there are no side effects, such as the direct modification of the input on.

How is Node.js date-fns installed?

date-fns, like most other JavaScript libraries, is available as an npm package and can be installed as such through npm. Use the command npm install date-fns in your project. The package is automatically entered as a dependency in your package.json file. Similarly, you can also use yarn with the yarn add date-fns command .
How is it used?

You can use the date-fns package with both the CommonJS module system and ES modules. In the following example, use the format function to print the current date. Listing 1 shows you how to work with the CommonJS module system.

const { format } = require('date-fns');

const date = new Date();

console.log(`Today is: ${format(date, 'DD.MM.YYYY')}`);

Newer versions of Node.js now also support the import and export keywords to import or export modules. At this point you can either import the entire date-fns package and access the required functions, or you can take advantage of the fact that each function is available in a separate file, so you can import the format function individually. How this works can be seen in example 2.

import { format } from 'date-fns/format';

const date = new Date();

console.log(`Today is: ${format(date, 'DD.MM.YYYY')}`);

Formatting of dates

With format you already know the most important function for formatting date values. The format string lets you specify which part of the date you want to format. For a comprehensive reference of each token that you can use in the format string, see https://date-fns.org/docs/format.

In addition to this function, you have access to other auxiliary functions, such as the distanceInWords function, which outputs the difference between two dates in readable form.
date arithmetic

An already mentioned vulnerability of the Date object in JavaScript is the lack of support for date arithmetic. So it is not easily possible to perform addition or subtraction. date-fns offers a number of auxiliary functions. In general, these functions follow a common naming scheme: First, you specify the operation followed by the unit that you want to work with. This results in function names such as addMinutes or subYears . All functions in this category accept as the first argument a date object and secondly a number that indicates how many units you want to add or subtract. For example, to add up to three quarters of an hour to the current date, you can use the code in example 3.

const { addMinutes, addHours, format } = require('date-fns');

const date = addMinutes(addHours(new Date(), 1), 45);

console.log(format(date, 'DD.MM.YYYY HH:mm'));

Comparisons

Also very helpful are the comparison functions of Node.js date-fns, with which you can determine if one date lies before or after another, or if there is a certain date in the future or in the past. The example of the functions isAfter and isFuture shows you how to use them in example 4.

const { isAfter, isFuture, addHours } = require('date-fns');

const date1 = new Date();
const date2 = addHours(new Date(), 5);

console.log(`Date1 is ${isAfter(date1, date2) ? 'after' : 'before'} Date2`);
console.log(`Date2 is ${isFuture(date2) ? 'not' : ''} in the past`);

Further operations

The date-fns package not only gives you simple operations such as addition, but also has more advanced operations, such as the areRangesOverlapping function, which you can use to determine if there are two overlaps.

With the min and max functions, you can find the earliest or latest date from a series of dates.

You can also use the compareAsc and compareDsc functions to sort arrays of dates. This function is passed as a comparison function to the sort method of an array. An example of this can be found in example 5.

const { compareAsc } = require('date-fns');

const sortedDates = [
new Date(2001, 1, 1),
new Date(2003, 3, 3),
new Date(2002, 2, 2),
].sort(compareAsc);

console.log(sortedDates);

Conclusion

Much of what packages like Moment.js or Node.js date-fns can offer you can also be achieved with native JavaScript. However, in these cases, the readability of the source code suffers greatly. This is one of the key arguments in addition to solving the peculiarities of the JavaScript Date object for using these libraries.

The possibilities of date-fns shown here are only a small part of the library and are just a foretaste of the functionality of this library. With numerous enhancements and a very good support of internationalization in applications, you should at least make a shortlist of date-fns the next time you are faced with choosing a date library for one of your applications.

Recent Articles

Best Programming Languages for Blockchain

Which are these the best programming languages for blockchain? Developers are presently utilizing prevalent programming languages like C++ and Java to manufacture custom blockchain...

Social VR world: Facebook Horizon should start in 2020

Facebook has announced with Horizon a new social VR world. This should allow users to create their own virtual reality worlds. The stop, however,...

Angular 9 Next Versions: Ivy, Bazel and more

Angular 9 next versions are here. Besides updates to Ivy, the update includes three features for the Language Service and Service Worker and changes...

Google Releases Dart 2.5: Code Completion through Machine Learning

The latest version of Googles C-Alternative, Go 1.13, is barely released, as the JavaScript derivative of the Internet giant follows: Dart 2.5 is here!...

Laravel 6.0 is here: Support for Serverless Platform Laravel Vapor

A new update is available for the framework Laravel. Laravel 6.0 is compatible with Laravel Vapor, a serverless deployment platform. The development team has...

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here