Библиотека date fns как сделать таймер
Перейти к содержимому

Библиотека date fns как сделать таймер

Javascript Dates Manipulation with 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 moment

date-fns@2.16.1 date-fns

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 npm-download-insights
  • GitHub stats github-stats.png
  • Popularity and activity 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:

Как сделать обратный отчёт времени на JavaScript

В этой статье будет очень интересно, будет рассказываться как сделать JavaScript обратный отсчет времени до даты, при этом мы сделаем не только до дня, а ещё добавим отсчёт времени, плоть до минуты.

Ещё в конце будет можно скачать этот скрипт обратного отсчета времени на javascript для своего сайта, ещё можете посмотреть статью Как сделать таймер на JavaScript, в ней вы сделаете самый обычный таймер, без отсчёта до дней.

Для начала, как всегда начнём с HTML, тут всё просто.

Как можете видеть это обычный HTML документ, единственное, мы создаём в нём div элемент, с классом timer , туда будем выводить значение нашего таймера.

JavaScript:

Вот теперь самое главное, это сама логика программы, а точнее теперь делаем скрипт на JavaScript, но сначала посмотрим логику программы.

Также, если вы ни разу не работали с временем на JavaScript, то посмотрите этот сайт.

Логика программы:

Суть того, как будет работать наша программа в том, что мы будем брать настоящие время и вычитать его из той даты, до которой нам нужно посмотреть отсчёт, к примеру, дата следующего первая сентября и т.д..

Всё это должно работать в интервале в одну секунду, и так каждый раз программа будет брать настоящие время и вычитать его из конечной даты, пока результат не будет равен или меньше нуля, после таймер останавливается.

Таким образом у нас должен получится таймер на сайт javascript.

Код программы:

Теперь займёмся кодом программы.

Это начало программы, давайте разберём его. Сначала мы создаём переменную которая хранит в себе элемент, в который будем отображать наш отсчёт.

Потом идёт функция в которой будем вычитать время, из заданного нами времени, вычитает настоящие время.

Дальше идёт JSON массив или ассоциативный массив, в котором мы как раз и храним данные до куда нам нужно отсчитывать наш таймер, как можете заметить у меня это девятое Мая, потом создаём строку формата YYYY-MM-DDTHH:mm:ss , но вместо букв подставляем значения из массива.

Сам таймер:

Теперь пришло время сделать сам таймер в интервале.

Теперь разберём код, в начале мы берём настоящие время, потом получаем время до которого нужно сделать отсчёт, дальше вычитаем в нашей функции из назначенного времени, настоящие время, функция возвращает миллисекунды разности этого вычитания.

Проверяем, если миллисекунд меньше или равно нулю, то выключаем интервал и выводим сообщение, что время закончилось.

Если условие не срабатывает, то из разности получаем время, дальше идёт самое интересное, мы создаём строку для вывода таймера, разберём его по подробнее.

  • res.getUTCFullYear() — Получаем год, но в нашем коде вычитаем 1970, это нужно для того, чтобы отсчёт начинался с нулевого года, так как, по умолчанию год начинается 1970 года.
  • res.getUTCMonth() — Просто получаем номер месяца.
  • res.getUTCDate() — Получаем день, но из него вычитаем один, это нужно для того, чтобы не учитывался сегодняшней день, если этого не сделать, то дата всегда будет на один день больше, даже тогда, когда остались считанные минуты.
  • res.getUTCHours() — Получаем час.
  • res.getUTCMinutes() — Получаем минуты.
  • res.getUTCSeconds() — Получаем секунды.

Можете заметить что выводим время по UTC. Дальше выводим эту строку таймер.

Тест программы:

Программу мы делать закончили, теперь покажу как она работает. У меня сейчас 23:19, я ставлю время на 23:20.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *