📜 ⬆️ ⬇️

TempusJS - working with the date in javascript

Hello!
I often have to work with statistics and there is a lot of tied up on dates. Moreover, the same date can be used on the page in different formats (for example, convenient for the machine and convenient for the person). I think most of you are perfectly aware of all this horrifying code that comes from using a Date object.
For example, to get the current date in the format DD.MM.YYYY we need to do the following:
var d = new Date(), fd = d.getDate() + '.' + (d.getMonth()+1) + '.' + d.getFullYear(); 

And when such lines becomes a lot? Is it easy to remember that in javascript the month starts from scratch when you develop not only on it? Or that there are milliseconds, not seconds, like almost everywhere on the backend? Some of the tasks can be solved using the popular library Moment.js , but it works very slowly.
The library in question solves these problems.
If interested, I suggest you read this short review.



TempusJS is largely composed of syntactic sugar on the Date object, so it works very quickly. The syntax of the library itself is quite simple. For example, to write the previous example, you can:
 var fd = tempus().format('%d.%m.%Y'); 

Now about the speed. In the spoiler you can see a comparison of Tempus with Moment and the native way of formatting the date (see above):
Comparison of native JS, MomentJS and TempusJS
We get the current date

 Native JS x 2,175,575 ops / sec ± 0.75% (96 runs sampled) 
 Moment x 284,864 ops / sec ± 0.85% (96 runs sampled) 
 Tempus x 2,086,081 ops / sec ± 0.73% (97 runs sampled)

')
Formatting

 Native JS x 1,637,517 ops / sec ± 0.61% (100 runs sampled) 
 Moment x 8,808 ops / sec ± 1.07% (100 runs sampled) 
 Tempus x 942,815 ops / sec ± 0.68% (94 runs sampled) 


Autodetect date and parsing

 Native JS x 11,204,316 ops / sec ± 0.81% (88 runs sampled) 
 Moment x 38.511 ops / sec ± 1.41% (95 runs sampled) 
 Tempus x 93,973 ops / sec ± 1.06% (85 runs sampled) 

Parsing date by format

 Moment x 46,293 ops / sec ± 0.63% (100 runs sampled) 
 Tempus x 109,947 ops / sec ± 0.93% (99 runs sampled) 

Parsing and validation

 Moment x 44,588 ops / sec ± 1.09% (90 runs sampled) 
 Tempus x 103,439 ops / sec ± 0.90% (94 runs sampled)

The results are obtained on my laptop in Google Chrome 30.0.1599.114. In other browsers, the results are different, but the ratio remains about the same.
The benchmark library was used for tests.
Benchmarks on other features, you can see here .


So, in the advantages of this library, you can write the following:


All functions of this library are described in the documentation . Also, there are tests on the site (if you find any error, please report it here .

Here we will discuss only some of the functions.

Formatting and parsing



So, for starters, another example of formatting a date. Here we also use a call chain. At the end of each value setting, we get back a TempusDate object, which we can use further in the chain. Example:
 tempus(). //    calc({month: -1}). //      format('%d.%m.%Y'); //     

Thus, we get the same day, hour and second, but a month ago. This is useful for receiving reports for the last month.

The next example is date parsing.
 //   TempusDate  "2013-11-18" tempus('18.11.2013'); //   TempusDate  "2013-12-12" tempus('2013-12-12', '%Y-%m-%d')); 

Tempus can automatically detect certain known formats. Also, you can specify a specific format, then the parsing will be faster. Plus, you can set the date to be returned if the parsing fails:
 // .. "123"     '%d.%m.%Y',  //   ,   2013-01-01 tempus('123', '%d.%m.%Y', tempus([2013, 1, 1])); 

The list of default formats can be found here.

And now we will change the format of the already formatted date.
 // '2013-11-05' tempus('05.11.2013').format('%Y-%m-%d'); //   // 'October, 12' tempus('2013-10-12 12:31:01', '%Y-%m-%d %H:%M:%S').format('%B, %d'); 


Also, you can use localization for formatting. By default, the user's language will be selected (taken from the browser) or the default language if the user's language is not found among the available Tempus languages.
 //   tempus.lang('ru'); //   format // ', 05' tempus(1383609600).format('%B, %d'); 

At the moment there are only two languages ​​- Russian and English, so I will be glad to help.

Validation


Validation of the date is as follows:
 //  false tempus('32.08.2013', '%d.%m.%Y').valid(); //  true tempus('00:00 01.01.2012', '%H:%M %d.%m.%Y').valid(); 


In case of an error, you can look at the fields in which it originated - wherever the value is not false:
 //  {"year":-5,"month":false,"day":false,"hours":false, // "minutes":false,"seconds":false,"milliseconds":false} tempus(). year(-5). //  =-5, ..  errors(); //     


Date ranges


Sometimes we need to get the number of years (for example, age), months, days, etc. between two dates. To do this, we can use the between method, which finds the difference between two dates and returns in the required format ('year', 'month', 'day', 'hours', 'minutes', 'seconds', 'milliseconds').
Here is a simple example of obtaining the number of months between November 1, 2013 and May 5, 2014:
 //  6 tempus([2013, 11, 1]).between(tempus([2014, 5, 5]), 'month'); 

Or how many hours are left until the new year
 tempus().between(tempus([2014]), 'hours'); 

In the last example, you can see that I have only indicated a year. When set by an array or object, missing values ​​will be
filled with the minimum. The list of constants with minimum values ​​can be seen in the documentation.

Also, we can change any date using the calc function:
 //  TempusDate   2012-01-01 tempus([2011, 5, 2]).calc({year: 1, month: -4, day: -1}); 


Own formats


We apply our format for the month, which can take values ​​from 1 to 12 (and not 01 to 12):
 //    tempus.registerFormat('%q', //  - %q function(date) { //    , ..     %q return date.month(); }, function(value) { //     var v = Number(value); return {month: (isNaN(v) ? undefined : v) }; }, 1, //  ,     2, //   'number' //  ); //  //  "01.1.2013"; tempus({year: 2013, month: 1, day: 1}).format('%d.%q.%Y'); //  {"year":2013,"month":2,"day":10,"hours":0,"minutes":0,"seconds":0}; tempus('10.2.2013', '%d.%q.%Y').get(); 

When registering, you will notice that some parameters are set separately, while you could use a regular expression. In fact, there it was originally there, but after abandoning it, the speed increased several dozen times.
If you need to remove some format, use unregisterFormat:
 tempus.unregisterFormat('%d'); //  "%d.01.2013", ..  %d   . tempus.format({year: 2013, month: 1, day: 1}, '%d.%m.%Y'); 


Getters / Setters


You can get / set some values ​​using the functions year (), month (), day (), hours (), minutes (), seconds (), milliseconds (), dayOfWeek (), utc (), timestamp () or set () For example:
 tempus(). //    year(1900). //    ,   1900  leapYear(); // ,    ,    false tempus().year(); //         


Date generation


You can generate a date in many ways, the full list of parameters is in the documentation. Here is a minimal example.
 // returns ["29.03.2013", "30.03.2013", "31.03.2013", "01.04.2013", "02.04.2013"]; tempus.generate({ dateFrom: '20130329', formatFrom: '%Y.%m.%d', dateTo: '20130402', period: {day: 1}, format: '%d.%m.%Y' }); 

This can be useful for displaying graphs by dates and changing the display format directly on the client, without queries to the backend. The date can be generated as an array, as well as objects, where the dates themselves will be the keys (this is useful when we need to attach an event to a date, for example, when we make our calendar). Also, dates can be grouped by day, week, month, hour, year - anything. This can also be applied to the calendar.

Plugins


And finally - plugins. Here we are expanding the factory to generate a random date. Also, we need the TempusDate class, which can be found in tempus.classes (). Here is an example of a plugin:
 (function (tempus) { var TempusDate = tempus.classes('TempusDate'); tempus.randomDate = function() { var date = new TempusDate(); date.year(Math.floor((Math.random()*(tempus.MAX_YEAR - tempus.MIN_YEAR)) + tempus.MIN_YEAR)). month(Math.floor((Math.random()*(tempus.MAX_MONTH - tempus.MIN_MONTH)) + tempus.MIN_MONTH)). day(Math.floor((Math.random()*(date.dayCount() - tempus.MIN_DAY)) + tempus.MIN_DAY)). hours(Math.floor((Math.random()*(tempus.MAX_HOURS - tempus.MIN_HOURS)) + tempus.MIN_HOURS)). minutes(Math.floor((Math.random()*(tempus.MAX_MINUTES - tempus.MIN_MINUTES)) + tempus.MIN_MINUTES)). seconds(Math.floor((Math.random()*(tempus.MAX_SECONDS - tempus.MIN_SECONDS)) + tempus.MIN_SECONDS)); return date; }; })(tempus); //        var someRandomDate = tempus.randomDate(); 

I think that this way you can conveniently write widgets using jQuery + Tempus, Angular + Tempus, etc.

Sources


You can install by downloading the sources from the githab:
https://github.com/crusat/tempus-js/releases
Or through bower:
 $ bower install tempus 

You only need one file - tempus.js or tempus.min.js.

I hope that this library will be useful, and it would also be interesting to find out what is missing in it to further develop the library in the right direction. Thanks for attention!
PS Thanks for the invite!

Source: https://habr.com/ru/post/204162/


All Articles