A closer look at date-fns
A year ago I wrote a blog post about Moment.js. A very popular date/time JavaScript library.
The problem with Moment.js is that it imports a monolithic object with all the methods. Even if you only need one or two methods, the application bundle contains everything. The library is not that big, and when your application uses much Moment.js functionality, it may not matter.
But when you only need one method, it would be nice if there is a way only to import this specific method. Here comes date-fns to the rescue. A collection of date/time functions that you can individually import into your application. In the documentation, they compare it with lodash but for date objects.
See also this discussion about the difference between date-fns and Moment.js
Size comparison
In this section, we create a simple application with both libraries and compare the bundle size of the packaged application. I use Parcel for the bundling process.
First, we create a new directory, and a package.json file with npm init -y . Then we install Parcel and the two libraries. For this test, I use Moment.js 2.24.0 and date-fns 2.0.0
Next, we create a directory src and add index.html, index-datefns.js, and index-moment.js. The examples make a few date calculations and print the result on the screen. You find the complete source code of the project on GitHub: https://github.com/ralscha/blog/tree/master/datefns
To build the two versions set the script tag in index.html to either <script src=»https://golb.hplar.ch/2018/01/index-datefns.js»></script> or <script src=»https://golb.hplar.ch/2018/01/index-moment.js»></script> and then call the bundler.
- Moment.js: 162 KB (Gzip: 42.2 KB, Brotli: 32 KB)
- date-fns: 37.3 KB (Gzip: 11.4 KB, Brotli: 9.41 KB)
The smaller size of the date-fns bundle is a result of the fact that the application only imported the required functions, with Moment.js the application imported the whole library.
Examples
In this section, we are taking a closer look at some functions date-fns provides. This is not a complete overview of all methods that are part of the date-fns library. See the official documentation for more details and a complete list of all provided methods.
As mentioned before, date-fns is a collection of independent date and time functions that you have to import into your application individually. date-fns does not provide a date/time wrapper, and it does not add any methods to the built-in Date object, but it works with the native Date object seeming less together.
Parameters
Almost all methods in the library take either a Date object or a number as a parameter. Internally date-fns converts these parameters to a Date object with the toDate functions. If you have a date string, you need to convert that manually with the parseISO function.
The toDate function returns a clone when a Date object is passed to the function. All the functions in date-fns are immutable and don’t change the parameters.
When a number is passed to the function, it is treated as a number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC.
When you have functions that expect multiple parameters, you can either provide arguments of the same type or mix the different types.
Time Units
Instead of providing one function that supports multiple time units, date-fns provides multiple variants of a function. For example the add* function exists in these variants: addMilliseconds , addSeconds , addMinutes , addHours , addDays , addWeeks , addMonths , addQuarters , addYear and addISOYears .
Not every function supports every time unit.
Parsing and Formatting
Converting a String to a Date object and vice versa is a common task in applications. For converting a String into a Date object date-fns provides the parse function.
parse requires three parameters. The input string to be parsed, the description of the format as string and the baseDate. The function returns a Date object when it is able to parse the string successfully.
parse supports a wide variety of format tokens. See the official documentation for a complete overview.
The third parameter (baseDate) is used when you parse partial dates like in this example.
The year is taken from the third parameter.
Reversely, from Date to string, we can use the format function. The format string (2nd parameter) supports the same tokens as parse .
Set and Get
The set* and get* functions set a time unit to a specific value. As mentioned before, date-fns does not change parameters, so the set* functions always return a new Date object with the changed value.
Note that months are 0 based, quarters start with 1.
Comparing
date-fns provides comparing functions like isAfter , isBefore and isEqual that check if the first date is after, before, or equal the second date.
For specific units, a isSame* function exists that checks if the specific unit is the same in the two provided dates.
Arithmetic
The add* and sub* functions add and subtract a certain amount of a specific unit. Like the set* functions, these functions don’t mutate the provided parameter; instead, they return a new Date object.
Weekdays
For weekdays some special functions return the weekday and check if a date falls on a specific weekday. The getDay function returns a number between 0 = Sunday and 6 = Saturday. For each weekday a is* function exists and isWeekend to check if a date falls on a weekend (Saturday or Sunday)
Intervals
date-fns supports a particular interval type that combines two dates. An interval object has two properties: start and end . Both properties can hold a Date or a number.
date-fns provides four functions that take intervals as parameters
areIntervalsOverlapping : checks if two intervals overlap
eachDayOfInterval : returns an array of dates with each day of the interval.
getOverlappingDaysInIntervals : returns the number of days that two intervals overlap.
isWithinInterval : checks if a date is within an interval
Difference
The difference* functions return the difference between two dates in a specific unit.
For days, weeks, months, quarters, and years two functions calculate the difference. The differenceInCalendar* functions only look at the specific unit and return the difference. The other differenceIn* functions return the difference in full days, weeks, months, quarters, and years. For instance, differenceInDays calculates how many full days (24 hours) are between the two dates.
Another everyday use case is representing the difference between two dates in words, like «3 days» or «in 20 minutes». For this use case date-fns provides three functions.
The function adds the word ‘ago’ and ‘in’ when addSuffix is set to true
When includeSeconds is true, the string contains a more detailed message when the difference is less than a minute.
formatDistanceStrict : Like formatDistance but does not add words like ‘almost’, ‘over’ or ‘less than’.
formatRelative : This function returns a string for the last and next 6 days like ‘last Sunday’, ‘yesterday’, ‘Tuesday’. For all the other dates it returns MM/dd/yyyy
Internationalization
The library contains translations for several languages. See the documentation for a list of all currently supported language.
To use a translation, you need to import the locale object
and then pass it as an option to a function:
Only format , parse , formatDistance , formatDistanceStrict and formatRelative support internationalization.
Countdown in date-fns with years, months, days, hours & minutes
I’m using DateFNS and I need to generate a countdown with it. distanceInWordsToNow only outputs in about 3 years but I need the exact time like 3 Years, 11 Months, 20 Days, 3 Hours, 2 Minutes . How to archive that with DateFNS?
![]()
3 Answers 3
The formatDuration() function in date-fns v2 does exactly what you want it to.
You can even filter it.
You can try something like this:
The idea is to run through all the time periods you want (and have supported date-fns functions) and generate an array with all the strings. We do this by running the supported differenceIn<PARTGOESHERE> first to get the time distance and then subtract it using the sub<PARTGOESHERE> function. After that just join them to compose the final string.
From here you can customize and export the parts as a parameter, as well as the uppercasing of the first letters in the output etc etc.
Here is also a lodash version:
![]()
Use the following dateFns functions to get the components, then concatenate them together with the strings.
let x be the smaller year, y be the larger save differenceInYears called on x and y which gives the whole number of years in a variable pass x and that as a parameter to addYears, assign to x
call differenceInMonths on x and y, save call addMonths on x and that saved number of months
do the same with differenceInDays and addDays, differenceInHours and addHours Now x is less than 60 minutes away from y, so call differenceInMinutes and you’re done (assuming your countDown is down to the minute).
Библиотека date fns как сделать таймер
At times during the development process, we constantly run into date objects . We need tools to assist us in handling those instances. There are two big players (Moment.js and date-fns) when it comes to JavaScript date management. This article will cover the basic applications of date-fns.
What is Date-fns?
Date-fns is a lightweight library that provides comprehensive functions for date formatting and manipulation. It is a simple to use API with many small functions to work with. Date-fns is termed to be Lodash for dates with over 140 functions.
Why Date-fns ⚡
- Immutable and pure — date-fns has pure built-in functions that return a new date instance rather than modifying the parsed date. This helps reduce and prevent bugs.
- Native Date — date-fns uses existing native JavaScript date API.
- Modular — you pick what you need, date-fns only imports the functions you need rather than the whole API functions pack. It works well with module bundlers such as webpack, Rollup, and Browserify. It also supports the tree-shaking algorithm.
- Fast — date-fns is a small API that is very light, thus guaranteeing users the best experience.
- Documentation — date-fns has well-outlined documentation with very clear and simple instructions to follow along. It also has use-case examples (code snippets) for every date function.
- I18n — perhaps you want to display dates with your users’ favorite locale. Date-fns has a dozen locales to work with whenever you need them.
- Typescript and Flow — supports both typescript and flow.
For more benefits on date-fns check this article out.
Getting Started with Date-fns
Date-fns is available in the npm packages collection. If you have Node.js installed, you can install date-fns using the command npm install date-fns .
If you are using yarn yarn add date-fns will get you started. Date-fns can be used with both CommonJS Modules and ES modules.
In this article, we will dive into the CommonJS module with date instances such as:
- Displaying dates
- Date formatting
- Date locale
- Time zones
- Date arithmetic
- Date comparisons, and other important applications of date-fns functions
Date Format
Date formatting is key when displaying a date. Formatting helps display human-readable dates. Date format replaces the individual date tokens to a format string. Formats specify the part of the date token you want to format and how the token will be displayed. To understand this better let’s have a look at some date token representation patterns that you can choose to display as formats.
Note: Some of these Unicode patterns are different from other date libraries such as Moment.js.
- y — 0, 1, 2, 3, 4, …, 17, 18, 1900, 2000, 2001, 2022, 2023, …
- yo — 0th, 1st, 2nd, 3rd, 4th, …, 15th, 16th, 17th, 19th, 20th, …
- yy — 00, 01, 02, 14, …, 15, 16, 17, 19 and 20, 21, 22, …
- yyy — 000, 001, 002, …, 014, …, 2017, 2018, 2019, 2020, 2021, 2022, 2023, …
- yyyy — 0000, 0001, 0002, …, 0014, …, 2017, 2018, 2019, 2020, 2021, 2022, 2023, …
- M — 1, 2, 3, 4, …, 10, 11 and 12
- Mo — 1st, 2nd, 3rd, …, 4th, 10th, 11th, 13th and 12th
- MM — 01, 02, 03, 04 …10, 11 and 12
- MMM – Jan, Feb, Mar, Apr, …, Oct, Nov and Dec
- MMMM – January, February, March, April, …, October, November and December
- MMMMM — J, F, M, A, M, J, J, A, S, O, N and D
- d – 1, 2, 3, 4, …, 28, 29, 30 and 31
- do — 1st, 2nd, 3rd, 4th, …, 29th, 30th and 31st
- dd — 01, 02, 03, 04, …, 28, 29, 30 and 31
- D – 1, 2, 3, 4, …, 362, 363, 364 and 365
- Do — 1st, 2nd, 3rd, 4th, …, 362nd, 363rd, 364th and 365th
- DD – 01, 02, 03, 04, …, 362, 363, 364 and 365
- DDD – 001, 002, 003, 004, …, 362, 363, 364 and 365
- E..EEE– Sun, Mon, Tue, Wed, Thu, Fri and Sat
- EEEE – Sunday, Monday, Tuesday, Wednesday, Thursday, Friday and Saturday
- EEEEE – S, M, T, W, T, F, and S
- EEEEEE – Su, Mo, Tu, We, Th, Fr and Sa
- H – 0, 1, 2, 3, 4, …, 19, 20, 21, 22 and 23
- Ho – 0th, 1st, 2nd, 3rd, 4th, …, 19th, 20th, 21th, 22nd and 23rd
- HH – 00, 01, 02, 03, 04, …, 19, 20, 21, 22 and 23
- h – 1, 2, 3, 4, …, 11 and 12
- ho – 1st, 2nd, 3rd, 4th, …, 11th and 12th
- hh – 01, 02, 03, 04, …, 11 and 12
- m — 0, 1, 2, 4, …, 54, 55, 55, 57, 58 and 59
- mo –0th 1st, 2nd, 3rd, 4th, …, 12th, 58th,59th
- mm — 00, 01, 02, 04, …, 54, 55, 56, 57, 58 and 59
- s – 0, 1, 2, 3, 4, …, 54, 55, 56, 57, 58 and 59
- so –0th 1st, 2nd, 3rd, 4th, …, 12th, 58th, 59th
- ss – 00, 01, 02, 03, 04, …, 54, 55, 55, 56, 57, 58 and 5
Parsing and Displaying Date
As we have explained, date-fns is a collection of many small functions. Use require(‘date-fn’); to get started. To start parsing and displaying dates you need to import the functions you require, thus you don’t have to import the whole API (only what you need). Let’s display simply today’s date.
This will display the default current date with the date-fns default format. format displays the date token to a more human-readable and looks exactly the way you want it (return the date parsed from string using the given format string).
Displaying Formatted Date
Alternatively, you can parse a default date value such as:
The examples above will display the date parsed with several date formats. Check out more date formats you can play with and get more ideas of how date-fns formats works.
Note: we have only imported the format function as it is what we need, that’s one of the dynamic features of date-fns. When formatting date-fns token values try to avoid some common mistakes such as:
These mistakes commonly occur if the Unicode patterns do not match to the correct date-fns Unicode tokens.
Date Arithmetic (additions, subtractions)
It is hard to do arithmetic calculations for dates. Date-fns simplifies addition and subtraction of dates between years, months, days, weeks, and seconds using simple functions such as addDays , addWeeks , addMonths , subDays , subWesks , subMonths etc.
Additions
Syntax: addDays(date, amount)
- date — The date to be changed
- amount — Amount of days to be added
Let’s perform simple date addition. To get started, import the add functions, then add the unit of time to the base date. Specify the operation you want to perform as the first argument followed by the number of units to add. Include the format function to format the date returned.
Note: Date units added/subtracted with positive decimals will be rounded off with math.floor and decimals less than zero will be rounded using math.cell .
Subtractions
Works exactly like addition, only that the add prefix function is replaced with a sub . Then subtract your specified units of time.
Syntax: subDays(date, amount)
Import sub function as shown in the example below. Similarly, you can choose format function to manipulate your display options.
Date Locale
Users who visits your website may come from different parts of the world. Assuming they do not speak your native language, how will you implement specifics or multiple locales to engage with those users?
Formatting dates was easy. How about locale? It cannot be that hard with date-fns, and it actually is as easy as pie. All you need is to import the locale plugin from date-fns.
Date-fns supports I18n to internationalize date functions and display localized formatted dates.
You need to use the require(‘date-fns/locale’); and pass the optional locales as the argument.
I.e. require(‘date-fns/locale/fr’); )(‘ fr for French’). For example, let’s have a simple date parsed and returned in French Locale.
Multiple locales example:
Check official doc to have a look at supported locale/supported-languages
Date Time Zones
Date-fns supports time zone data to work with UTC or ISO date strings. This will help you display the date and time in the local time of your users.
The difficulty comes when working with another time zone’s local time, for example showing the local time of an event in LA at 8 pm PST on a Node.js server in Europe or a user’s machine set to EST.
In this case, there are two relevant pieces of information:
- A fixed moment in time in the form of a timestamp, UTC or ISO date string, and
- The time zone descriptor, usually an offset or IANA time zone name (e.g. America/Los_Angeles)
Time Zone Helpers
To understand time zone helpers, assume you have a system where you set an event to start at a specific time and your system local time should be shown when the site is accessed anywhere in the world.
- zonedTimeToUtc returns a given date equivalent to the time zone UTC (parses date in a given time zone)
- utcToZonedTime return local time from a UTC (converts date to the provided time zone)
Example Use Cases
Below are some use cases for us to look at.
npm install date-fns-tz
Date Comparisons
Date-fns provides you with comparison functions that help you determine if a given time is before, after, or within another date period. Or if the given date lies in the past or in the future of the comparing date. Some of the commonly used comparing functions include:
isAfter
Checks if the first date is after the second and returns a Boolean value true if the first date exists after the second date and if false, the arguments are not true.
Syntax: isAfter(date, dateToCompare)
- Date — the date that should be after the second date (as the first argument)
- DateToCompare — the second date to be compared with the first date. (As the second argument)
Import the functions you need.
isBefore
Checks if the first date is before the second date.
isFuture
Checks if the given date is in the future in comparison to the date/time now.
Note: if the date we are comparing is the time right now, isFuture will return this as false. In such a case, date-fns will interpret the ‘now’ date as the present time and not a future time.
ASC and Desc
Compares a collection of dates and sort them in ascending or descending order.
There are many comparison function options such as:
isWeekend
Checks if a given date is a weekend.
isDate
Checks if a given string value is an instance of a date and returns true is the date provided is actually a date value.
Check out more comparison functions and helpers such as isPast, isEqual, isExits, isMatch, and many more.
Date Validation
Date-fns provides you with date validation helpers with the isValid() function that checks if a given date is valid.
By default, date-fns returns a Boolean variable true if the date parsed is indeed a valid date or false if the date string parsed is not a valid date.
However, in the example above, you will be surprised to find out the new Date (‘2020, 02, 30’) returns true yet the date itself is obviously invalid. There is no date with a February 30th day.
Interestingly, this is not a bug in date-fns. To elaborate this further enter a new Date (‘2020, 02, 30’) on your browser’s console (in my case I am using a Google chrome console).
This date instance will be interpreted as Sun Mar 01, 2020, 00:00:00 ‘2020, 02, 30’ . February ends on 29th (2020 is a leap year) and the extra day will be added to represent the date of the next month, which indeed will be valid.
To avoid such instances parse the date before checking the isValid() .
Lets run through another example:
Differences Between Dates
Date-fns provides several functions to manipulate and calculate the differences that exists between two given dates. These functions represent the difference between calculations for several units of time such as:
-
(number of seconds between given dates) (number of minutes between given dates) (number of days between given dates) (number of business days period between two given dates) (number of weeks between given dates) (number of years between given dates)
Each unit will get the number of the given unit differences between two dates.
Calculating the difference of days and the number of business days that exists between now and Christmas.
Date-fns Intervals
Date-fns provides you with interval helpers to combine two dates and determine the time interval between them. An interval object has two properties:
- Start — the start of the interval
- End — the end of the interval
This interval helper includes
-
— checks if the given time interval overlaps another time interval — gives an array of dates that exist within a specified interval — gives an array of hours that exist within a specified interval — gives an array of months that exist within a specified interval — gives an array of weeks that exist within a specified interval — gives an array of years that exist within a specified interval — determines if a given date is within a specified interval
Head to the date-fns docs to check out more interval helpers and how you can apply them to your application.
Comparison Between Moment.js and Date-fns
Moment.js is a stand-alone open-source JavaScript framework wrapper for date objects. It eliminates native JavaScript date objects, which are cumbersome to use. Moment.js makes dates and time easy to display, format, parse, validate, and manipulate using a clean and concise API. Unlike date-fns, its biggest downside is that its API size is huge. For more information on Moment.js, check out this article.
As we have seen in the examples above, date-fns is a collection of many small and independent functions allowing you to only import functions that are needed. Unlike Moment.js where you create a moment instance to run functions from it. With Moment.js, there isn’t a way to import a specified function. That means you have to import the whole API chain even when loading a simple date thus creating performance overheads.
Date-fns only grabs the specific function and this makes is a much smaller library than Moment.js.
moment@2.28.0 
date-fns@2.16.1 
Even so, if you love working with Moment.js, its size should not be a big concern. You can configure Moment.js with webpack to remove data that you aren’t using, such as locale plugins, and this will significantly reduce Moment.js bundle size.
Moment.js fits well when working with a big project because you will end up using much of Moment.js functionalities therefore the bundle size won’t matter. If you just want to load simple dates that need one or two methods then date-fns will definitely work in your favor.
If you are dealing with time zones, I would suggest you check out Moment.js. Its time zone functionalities are extensive compared to those of date-fns. Moment.js has more locale support functionalities to extend a more global reach with your date instances.
Statistical Comparison
- NPM download stats

- GitHub stats

- Popularity and activity popularity and activity

Date Manipulating Framework Alternatives
Day.js
⏰ Day.js is a 2KBs immutable date library alternative to Moment.js with the same modern API.
- Familiar Moment.js API & patterns
- Immutable
- Chainable
- I18n support
- 2kb mini library
- All browsers supported
Luxon
Luxon is a library that makes it easier to work with dates and times in JavaScript. If you wanted to have, add and subtract them, format and parse them, ask them hard questions, and so on, Luxon provides a much easier and comprehensive interface than the native types with features such as:
Работа с датами Использование date-fns в JavaScript
Работа с датами — непростая задача. Но пакет date-fns упрощает работу с датами в JavaScript.
Давайте углубимся в пакет date-fns, чтобы сделать нашу жизнь проще, чем раньше. Пакет date-fns легковесен.
Установка пакета
Нам нужно настроить проект с помощью npm для работы со сторонним пакетом. Давайте быстро рассмотрим шаги для завершения нашей настройки.
Я предполагаю, что у вас установлен NodeJS или IDE, чтобы попрактиковаться.
- Перейдите в нужный каталог, в котором вы хотите работать.
- Запустите команду npm init, чтобы инициализировать проект.
- Ответьте на все вопросы в зависимости от ваших предпочтений.
- Теперь установите date-fns, используя приведенную ниже команду.
- Создайте файл с именем dateFunctions.js
Теперь мы готовы перейти к пакету date-fns. Давайте пойдем и изучим некоторые основные методы из пакета.
является действительным
Все даты недействительны.
Например, нет такой даты, как 2021-02-30. Как мы можем проверить, действительна ли дата или нет?
Метод isValid из пакета date-fns поможет нам определить, действительна ли данная дата или нет.
Проверьте, нормально ли работает следующий код с правильностью дат.
Если вы выполните приведенный выше код, вы обнаружите, что 30 февраля 2021 года является действительным. Ой! Это не.
Почему это происходит?
JavaScript преобразует дополнительный день февраля в 1 марта 2021 года, что является допустимой датой. Чтобы подтвердить это, выведите в консоль новую дату («2021, 02, 30»).
Пакет date-fns предоставляет метод parse для решения этой проблемы. Метод parse анализирует дату, которую вы указали, и возвращает точные результаты.
Взгляните на приведенный ниже код.
формат
Одним из основных способов использования при работе с датами является их форматирование по своему усмотрению. Форматируем даты в разных форматах, используя метод format из пакета date-fns.
Отформатируйте дату как 23-01-1993, 1993-01-23 10:43:55, вторник, 23 января 1993 года и т. д.. Запустите следующий код, чтобы получить соответствующую дату в указанных форматах.
Вы можете найти полный список форматов здесь.
addDays
Метод addDays используется для установки крайнего срока, который наступает через некоторое количество дней.
Просто мы можем добавить дни к любой дате, чтобы получить дату дня через несколько дней. Он имеет множество приложений.
Допустим, у вас день рождения через X дней, и вы заняты в эти дни. Вы можете не помнить день рождения в своем плотном графике. Вы можете просто использовать метод addDays, чтобы уведомить вас о дне рождения через X дней. Имейте код.
Аналогично методу addDays существуют и другие методы, такие как addHours, subHours, addMinutes, subMinutes, addSeconds, subSeconds, subDays, addWeeks, subWeeks, addYears, subYears и т. д. Вы можете легко догадаться о функциональности методов по их именам.
форматРасстояние
Написание кода для сравнения дат с нуля — кошмар. Почему мы вообще сравниваем даты?
Есть много приложений, где вы видели сравнения дат. Если вы возьмете веб-сайты социальных сетей, в слогане будет упоминаться 1 минута назад, 12 часов назад, 1 день назад и т. Д. Здесь мы используем сравнение даты с даты и времени публикации до текущей даты и времени.
Метод formatDistance делает то же самое. Он возвращает разрыв между заданными двумя датами.
Давайте напишем программу для определения вашего возраста.
каждыйDayOfInterval
Допустим, вам нужно найти имена и даты следующих X дней. Метод eachDayOfInterval помогает нам найти дни между начальной и конечной датами.
Давайте узнаем ближайшие 30 дней с сегодняшнего дня.
макс и мин
Методы max и min находят максимальную и минимальную даты среди заданных дат соответственно. Методы в date-fns очень знакомы и легко догадаться о функциональности этих методов. Давайте напишем код.
равно
Вы можете легко догадаться о функциональности метода isEqual. Как вы думаете, метод isEqual используется для проверки того, равны ли две даты или нет. См. пример кода ниже.
Вывод
Если говорить о каждом методе в пакете date-fns, то на его выполнение уходят дни. Лучший способ изучить любой пакет — ознакомиться с его основными методами, а затем прочитать документацию для получения дополнительной информации. Примените тот же сценарий для пакета date-fns.
Вы изучили основные методы в этом уроке. Найдите конкретное использование в документация или подумайте о том, чтобы пройти онлайн-курсы, такие как JavaScript, jQuery и JSON.