Javascript at a specific time. TempusJS - working with date in javascript. Date autodetection and parsing


There is a special object for working with date and time in JavaScript - Date. This object is supported by almost all versions of JavaScript, and you can use it without looking back for compatibility issues.

Date and time in the Date object are not stored explicitly, but as in most programming languages \u200b\u200b- in the form of the number of milliseconds since the birth of Unix, i.e. from 0 hours 0 minutes January 1, 1970. A distinctive feature of the Date object is that all range values \u200b\u200bhave zero-based indices. This means that January will have index 0 (month # 0), and December will not be the twelfth, but the eleventh month. The same is true for the days of the week, hours, minutes, etc.

It is very easy to create a Date object:

// current date-time var date \u003d new Date (); // date-time from string or number var date \u003d new Date (date); // date-time from separate values \u200b\u200bvar date \u003d new Date (year, month, day, hour, minute, second, millisecond);

The Date object has a number of very useful methods that allow you to work with individual date-time components, as well as to check the correctness and display the correct date in a given format.

Methods for getting date-time components
getFullYear Returns the year (for example, 2011).
getYear Returns the year. The purpose of the getYear method is the same as the purpose of getFullYear, however, this method is deprecated and deprecated. the results of his work are ambiguous: for the date range from 1900 to 1999, the method returns the number of the year in the century (two-digit, for example, 77), and for dates outside this range, the full value (four-digit, for example, 2009) is returned.
getMonth Returns the month.
getDate Returns the day of the month (number in the month).
getHours Returns the hour.
getMinutes Returns the minute.
getSeconds Returns the second.
getMilliseconds Returns the millisecond.
getDay Returns the day of the week.
getTime Returns the millisecond offset stored by the object.
Methods for modifying datetime components
setFullYear Sets the year.
setYear Sets the year. The setYear method has the same function as setFullYear, but this method is deprecated and deprecated (as well as the getYear method).
setMonth Sets the month.
setDate Sets the date in the month (day of the month).
setHours Sets the hour.
setMinutes Sets the minute.
setSeconds Sets the second.
setMilliseconds Sets the millisecond.
setTime Sets millisecond offset from 00:00:00 01/01/1970
Date-Time Formatting and Output Functions
toString Returns a string representation of the date and time.
toUTCString Returns a string representation of the date and time converted to UTC time. The format of the returned string is based on all Internet standards.
toGMTString Returns a string representation of the date and time converted to GMT (Greenwich Mean Time). The format of the returned string is based on all Internet standards.
toLocaleString Similar to toString, but returns a string representation of the date and time formatted according to the user's localization settings.
toTimeString Returns a string representation of the time (the string contains only the time).
toDateString Returns the string representation of the date (the string contains only the date).
toLocaleTimeString Similar to toTimeString, but returns a string representation of the time formatted according to the user's localization settings.
toLocaleDateString Similar to toDateString, but returns a string representation of the date formatted according to the user's localization settings.
Additional functions
getTimezoneOffset Returns the offset of the local time on the user's computer relative to UTC. The offset is returned in minutes.
parse The function allows you to check the correctness of the date-time written as a string. If the string is correct, a Date object will be created immediately.

The Date object also contains a number of methods for working with UTC dates. These functions are completely similar to those already considered, but they contain the "UTC" prefix in the name and work only with "universal" time: getUTCSeconds, setUTCFullYear, etc.

Let's consider an example of working with dates:

And here is the result of this script:


As you can see, the representation of the date differs significantly depending on the format used. Therefore, when working with date-time, you must adhere to a few simple rules:

1. Use UTC or GMT formats whenever possible. This is especially important when creating distributed solutions (for example, clients of payment systems). Using a common reference time will give you guarantees (albeit not one hundred percent) that you and your remote partner will interpret the received data in the same way.

2. It makes sense to use localized date and time only when displaying them to the user. In all other cases, it is better to refuse localized data.

3. If you still have to use a local date and time - do not forget to take into account the offset of the local time relative to the reference time (UTC or GMT).

Following these rules will save you from most logical bugs and shortcomings, which means it will make your code more stable and of high quality.

It is rare for a programmer to avoid working with dates and times. In general, date / time is a basic concept, and in most languages \u200b\u200bthere are built-in mechanisms for working with this data type. It would seem that JS is no exception, there is a built-in Date type, there are a bunch of functions in the prototype, however ...

Who's guilty
The first problem occurs when you need to set the date / time in a time zone other than UTC and local. The Date constructor has no such parameter.

New Date (); new Date (value); new Date (dateString); new Date (year, month [, day [, hour [, minute [, second [, millisecond]]]]]);
The only option where you can specify an offset relative to UTC is the third way. Calling the constructor in this format allows you to pass the offset as part of the string:

New Date ("Sun Feb 01 1998 00:00:00 GMT + 0700")
The string is accepted in RFC2822 format, which is very inconvenient and difficult for manual input. It is almost impossible to get such a string from user input. I cannot imagine a person who would agree to enter a date in this format.

Despite the fact that in Date you can set all the parameters separately for the UTC timezone - this does not solve the problem - the timezone will remain local. But this is not the only problem.

UTC offset is not constant. This is a function of date, time (or from a timestamp, if you like) and, again, a time zone. For example, for Moscow, the last time translation gives:

New Date (2014, 9, 25, 0, 0, 0); // 26.10.2014, 21:00:00 GMT + 3 new Date (2014, 9, 27, 0, 0, 0); // 25.10.2014, 22:00:00 GMT + 4
Thus, the constructor in the third option becomes almost useless since the offset must be known in advance. And it, as has been said, cannot be obtained so easily. The only library I came across that uses Olson's database to calculate shifts is timezone-JS. The problem with using this library is that the underlying libraries (date / time pickers) know nothing about it and actively use the standard Date internally. The rest of the libraries working with the Date object do not explicitly refer to this base and do not receive updates from it. (Correct me in the comments.)

In business applications, time zones are only meaningful if the date and time are specified. For example, if the working day starts at 9:00, then you hardly expect your colleague from Vladivostok to start working at 15:00. Timezones should not be taken into account and in this case the date should be displayed in UTC. However, in the case of regular events occurring at the same time in different time zones, a time zone is still needed. For example, your daily scrum starts at 10:00 for you and at 13:00 for Novosibirsk. By the way, this is exactly the difference between GMT and UTC. UTC is time with no offset, and GMT is time with offset 0. Let me explain with an example:

12/31/2014 20:59:59 GMT in the Moscow time zone should look like 12/31/2014 23:59:59 12/31/2014 20:59:59 UTC in the Moscow time zone should look like 12/31/2014 20:59 : 59
Because of this arithmetic, they are mostly confused. Unfortunately, this parameter is confused all over the place. The absence of a direct indication of the timezone in JS is interpreted as a local timezone, and the indication of UTC and GMT is equivalent.

Intl. I could, but I don't have to. In particular, there is such a timeZone parameter, but, a little further, the standard defines: The time zone to use. The only value implementations must recognize is "UTC". Currently, apart from Chrome, no other browser supports arbitrary timezones.
With time ranges in JS, everything is really bad - there is nothing like this in the language. If you want to do well, do it yourself.

What to do
  • Option 1.
    Do not use an arbitrary time zone. The preferred option and, probably, the most painless. That is, you only have the local timezone and UTC. For these cases, all browsers seem to have everything, albeit not very convenient. In addition, the time zone is set globally for the OS and it is not kosher to change it for a specific web application.
  • Option 2.
    If arbitrary time zones are needed, do not use a time stamp. Absolutely. Store the time in the savings bank in the RFC line with the timezone. I'm not sure if this will help to defeat timezone shifts in a cross-browser understanding, but at least Chrome is aware of such shifts.
  • Option 3.
    Situations are different and it happens that the time is recorded in the database from any device. That is, in the form of a time stamp. There is nowhere to run, in order to correctly display the time, you need to know either the device's time zone, or the user's time zone, or both, and calculate all the shifts hand-to-hand. You can't do without the use of Olson's base.
  • There should be the moral of this fable, but I have nothing more to add. I don't see any progress in the drafts of the ECMA standard, probably there won't be any.

In this lesson, we will introduce the JavaScript Date object and learn how to use it in practice.

Date creation - 4 examples

In JavaScript, date creation is done using the Date object. The Date object represents a point on the time axis and is designed to store dates and times with millisecond precision.

Examples of creating a date in JavaScript.

1. Creation of the current date and time.

Get the current date and time in JavaScript is done by instantiating a Date object without specifying parameters:

// the current date (the date and time that was at the moment of creating an instance of the Date object on the user's local computer) var now \u003d new Date (); // for example, print the current date to the console console.log (now);

If you need to get only today's date in string format, you can use the toLocaleDateString method:

Var now \u003d new Date (). ToLocaleDateString (); // 19.12.2019

The user's current time can be obtained like this:

Var now \u003d new Date (). ToLocaleTimeString (); // 11:02:48 var now \u003d new Date (). ToLocaleTimeString (). Slice (0, -3); // 11:02

The date and time in string format can be obtained as follows:

Var now \u003d new Date (). ToLocaleString (); // 19.12.2019, 11:02:48

2. Creation of a date by specifying the number of milliseconds to the Date object since January 1, 1970 00:00:00 UTC.

// 1 year (not high-speed) \u003d 365 * 24 * 60 * 60 * 1000 \u003d 31536000000 ms // for example, let's create the date 01/01/1971, 00:00:00 UTC: var date1 \u003d new Date (31536000000);

3. Creation of a date by specifying it to a Date object as a string.

With this option for creating a date, JavaScript will try to understand the string passed to it and form a date based on it. Converting a string to a date in JavaScript is done using the Date.parse method.

For instance:

// create a date based on a string in DD.MM.YY format var date1 \u003d new Date ("05.11.19"); // create a date based on a string in the format YYYY-MM-DDThh: mm: ss.sss (T is used to separate date and time) var date2 \u003d new Date ("2015-02-24T21: 23"); // create a date based on a string indicating the time zone (format YYYY-MM-DDThh: mm: ss.sss ± hh: mm): var date3 \u003d new Date ("2015-02-24T22: 02 + 03: 00") ;

4. Creating a date by specifying the following parameters, separated by commas: year (4 digits), month (counting from 0), day (1..31), hours (0..23), minutes (0..59), seconds (0..59), milliseconds (0. .999). Moreover, only the first two parameters are required.

An example of creating a date with only required parameters:

// create date 01.01.2015 (unspecified parameters are by default equal: number - 01, hours - 00, minutes - 00, seconds - 00, milliseconds - 000). var date1 \u003d new Date (2015.01); // create a date on 01.24.2015, 21:23 var date2 \u003d new Date (2015,01,24,21,23);

Note: If you need to set the date and time in UTC, you can use the Date.UTC method.

// 1 example var date1 \u003d Date.UTC (2015,1,1); var date2 \u003d new Date (date1); alert (date2.toUTCString ()); // 2nd example var newDate \u003d new Date (Date.UTC (2015,1,1)); alert (newDate.toUTCString ());

Retrieving Individual Date and Time Components

JavaScript uses the following methods to get the individual date and time components:

  • getFullYear () - returns a 4-digit year;
  • getMonth () - returns the month in the format of a number from 0 to 11 (0 - January, 1 - February, 2 - March, ..., 11 - December);
  • getDate () - returns the day of the month from 1 to 31;
  • getHours () - returns the number of hours from 0 to 23;
  • getMinutes () - returns the number of minutes from 0 to 59;
  • getSeconds () - returns the number of seconds from 0 to 59;
  • getMilliseconds () - Returns the number of milliseconds from 0 to 999.

All of these methods return separate date and time components according to the time zone set on the user's local device.

// create the date 11/11/2019 00:00 UTC var newDate \u003d new Date (Date.UTC (2019,11,11)); // get the date components if the local time on the user's device is UTC + 10: 00 newDate.getFullYear (); // 2019 newDate.getMonth (); // 10 newDate.getDate (); // 11 newDate.getHours (); // 10 newDate.getMinutes (); // 0 newDate.getSeconds (); // 0 newDate.getMilliseconds (); // 0

An example in which we will greet the user depending on what time interval he currently has:

// get the user's current time and components of this time var now \u003d new Date (), hour \u003d now.getHours (), minute \u003d now.getMinutes (), second \u003d now.getSeconds (), message \u003d ""; // define a greeting phrase based on the user's local time if (hour<= 6) { message = "Доброе время суток"; } else if (hour <= 12) { message = "Доброе утро"; } else if (hour <= 18) { message = "Добрый день"; } else { message = "Добрый вечер"; } // выполним форматирование времени с использованием тернарного оператора minute = (minute < 10) ? "0" + minute: minute; second = (second < 10) ? "0" + second: second; hour = (hour < 10) ? "0" + hour: hour; message += ", сейчас " + hour + ":" + minute + ":" + second; // выведем приветствие и время в консоль console.log(message); // Добрый вечер, сейчас 22:50:39

In this example, the time is displayed in the desired format using the ternary operator.

JavaScript has analogues for these methods for getting the individual date and time components for the UTC + 0 time zone. These methods are named similarly, but with "UTC" added after "get": getUTCFullYear (), getUTCMonth (), getUTCDate (), getUTCHours (), getUTCMinutes (), getUTCSeconds (), getMilliseconds ().

You can get the day of the week in JavaScript using the getDay () method.

This method returns a number from 0 to 6 (0 - Sunday, 1 - Monday, ..., 6 - Saturday).

An example in which we convert the day of the week from numeric to string representation:

Var days \u003d ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; // get the current date var now \u003d new Date (); // print the day of the week to the console console.log ("Today" + days);

You can get the number of milliseconds that have passed since 01/01/1970 00:00:00 UTC in JavaScript using the getTime () method.

You can find out the difference (in minutes) between the local device time zone and UTC in JavaScript using the getTimezoneOffset () method.

Setting the individual date and time components

In JavaScript, you can set individual date and time components using the following methods on the Date object:

  • setFullYear (year [, month, date]) - setting the year (in addition, you can set another month and day);
  • setMonth (month [, date]) - setting the month from 0 to 11 (0 - January, 1 - February, 2 - March, ..., 11 - December); additionally, this method allows you to set the number;
  • setDate (date) - setting the number;
  • setHours (hour [, min, sec, ms]) - sets the hour from 0 to 23 (you can additionally set minutes, seconds and milliseconds);
  • setMinutes (min [,) - sets minutes from 0 to 59 (you can additionally set more seconds and milliseconds);
  • setSeconds (sec,) - sets seconds from 0 to 59 (additionally, you can set more milliseconds);
  • setMilliseconds (ms) - Sets milliseconds (0 to 999).

All of these methods are designed to set the date and time in the time zone set on the user's computer.

// create an instance of a Date object containing the current date var newDate \u003d new Date (); // set the year newDate.setFullYear (2019); // set the year and month newDate.setFullYear (2019, 08); // set 20.09.2019 newDate.setFullYear (2019, 08, 20); // set the month newDate.setMonth (05); // set month and day newDate.setMonth (05, 15); // set the number newDate.setDate (28); // set the hour newDate.setHours (13); // set the hour and minutes newDate.setHours (13,20);

In JavaScript, setting the date and time in UTC + 0 time zone is done using the following methods: setUTCFullYear (), setUTCMonth (), setUTCDate (), setUTCHours (), setUTCMinutes (), setUTCSecondes (), setUTCMilliseconds ().

Setting the date and time using the number of milliseconds since 01/01/1970 00:00:00 UTC is done using and then setTime ().

In addition, in JavaScript, specifying incorrect date and time components does not lead to errors, they are simply automatically distributed among the rest.

For instance:

// number 44 will be distributed as follows: 44 - 31 \u003d 13, 13 February 2019 newDate.setFullYear (2019, 01, 44);

This technique can be used when you need to get a date that differs from the given one for a certain period of time.

// date that will be 7 days greater than newDate newDate.setDate (date1.getDate () + 7); // date that will be less than newDate by 120 seconds newDate.setSeconds (date1.getSeconds () - 120); // this way you can set the last day of the previous month for newDate newDate.setDate (0);

Date to string conversion and formatting

In JavaScript, methods for converting a date to a string can be divided into 2 groups.

The first group includes methods that do this the way it is defined in the browser: toString (), toDateString (), toTimeString (), toUTCString ().

The toString () method returns the full date representation, toDateString () - the date only, toTimeString () - the time only, toUTCString () - the full date representation, but in UTC + 0 time zone.

Because the string representations that these methods should return are not clearly defined in the standard, they may differ in different browsers.

To the second group methods can be assigned taking into account the time zone and language of the local computer: toLocaleString () - date and time, toLocaleDateString () - only date, toLocaleTimeString () - only time.

The toLocaleString (), toLocaleDateString (), toLocaleTimeString () methods have 2 optional parameters. The first parameter is for explicitly specifying the locale, the second is for specifying formatting options.

If the locale is not explicitly set or undefined, then the browser takes the one it has by default.

In addition, JavaScript also has a toISOString () method. It returns a string containing the date and time in ISO format (YYYY-MM-DDTHH: mm: ss.sssZ).

// create the date 04/15/2019 18:43:59 (in the user's time zone) var newDate \u003d new Date (2019, 03, 15, 18, 43, 59); console.log (newDate.toString ()); // Mon Apr 15 2019 18:43:59 GMT + 1000 (Vladivostok Standard Time) console.log (newDate.toDateString ()); // Mon Apr 15 2019 console.log (newDate.toTimeString ()); // 18:43:59 GMT + 1000 (Vladivostok, standard time) console.log (newDate.toLocaleString ()); // 04/15/2019, 18:43:59 console.log (newDate.toLocaleDateString ()); // 04/15/2019 console.log (newDate.toLocaleTimeString ()); // 18:43:59 console.log (newDate.toUTCString ()); // Mon, 15 Apr 2019 08:43:59 GMT console.log (newDate.toISOString ()); // 2019-04-15T08: 43: 59.000Z

Method to convert string to date

JavaScript uses the Date.parse () method to convert a string to a date. This method can convert a string if it is RFC2822 or ISO 8601 compliant.

In this lesson, consider the ISO 8601 standard, which requires a string to be in the following format: YYYY-MM-DDThh: mm: ss.sssZ.

  • YYYY - 4-digit year;
  • MM - a 2-digit month (01 \u003d January, 02 \u003d February, etc.);
  • DD - day of the month, consisting of 2 digits (01..31);
  • T - character for separating date and time;
  • hh - number of hours (00..23);
  • mm - number of minutes (00..59);
  • ss - number of seconds (00..59);
  • sss - number of milliseconds (0..999);
  • Z is a character that means that the time is specified in UTC format. If you need to set the time zone instead of UTC, then the letter "Z" should be replaced with the value + hh: mm or -hh.mm.

If the string containing the date and time is not in RFC2822 or ISO 8601 format, then JavaScript's Date.parse () method can still convert it, but the result in this case may be unpredictable.

Hello!
I often have to work with statistical data and there is a lot of it tied to dates. Moreover, the same date can be used on the page in different formats (for example, convenient for a car and in a convenient for a person). I think that most of you are perfectly aware of all this horrifying code that comes with 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 \u003d new Date (), fd \u003d d.getDate () + "." + (d.getMonth () + 1) + "." + d.getFullYear ();
And when there are many such lines? Is it easy to remember that in javascript a month starts from scratch when you develop not only in it? Or the fact that there are milliseconds, not seconds, like almost everywhere on the backend? You can solve some of the tasks with the popular Moment.js library, but it works very slowly.
The library in question solves these problems.
If interested, I suggest you read this small review.

TempusJS is a lot of syntactic sugar on the Date object, so it's very fast. The syntax of the library itself is quite simple. For example, you can write the previous example like this:
var fd \u003d tempus (). format ("% d.% m.% Y");
Now about the speed. In the spoiler, you can see a comparison of Tempus with Moment and the native date formatting (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)
Date autodetection 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 a 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 were obtained on my laptop in Google Chrome 30.0.1599.114. In other browsers, the results differ, but the ratio remains roughly the same.
The benchmark.js library was used for the tests
Benchmarks for other features, you can see.

So, the advantages of this library can be written as follows:

  • Supports IE6 +, Chrome, Firefox, Opera;
  • Supports call chains;
  • Months can start with 1 (default) rather than zero;
  • Milliseconds can be disabled (default) or enabled;
  • Fast work (Since, in many cases, the browser native Date object is used, the implementation of which is written in faster languages);
  • Supports custom formats and plugins
  • Date validation is very fast and depends only on the functions that set the date (since the validation takes place already when the values \u200b\u200bare entered, and is not calculated separately);
  • Multilanguage and autodetection of the user's language.

Here we will only talk about some of the functions.

Formatting and parsing

So, for starters, another example of date formatting. We also use call chaining here. At the end of each setting, we get back a TempusDate object that we can use further down the chain. Example:
tempus (). // get the new date calc ((month: -1)). // decrease it by one month format ("% d.% m.% Y"); // Output as a string
Thus, we get the same day, hour and second, but a month ago. This is useful for getting reports for the last month.

The next example is parsing a date.
// Returns a TempusDate object with the date "2013-11-18" tempus ("11/18/2013"); // Returns a TempusDate object with the date "2013-12-12" tempus ("2013-12-12", "% Y-% m-% d"));
Tempus can automatically detect some known formats. Also, you can specify a certain format, then the parsing will be faster. Plus, you can set the date that will be returned if the parsing fails:
// Because "123" does not match the format "% d.% M.% Y", then // an object containing the date 2013-01-01 will be returned tempus ("123", "% d.% M.% Y", tempus ());
The list of default formats can be viewed

Now let's change the format of the already formatted date
// "2013-11-05" tempus ("05.11.2013"). Format ("% Y-% m-% d"); // Or so // "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.
// Set the language tempus.lang ("ru"); // By default we use format // "November 05" tempus (1383609600) .format ("% B,% d");
At the moment, there are only two languages \u200b\u200b- Russian and English, so I will be glad to help.

Validation

Date validation is as follows:
// Returns false tempus ("08/32/2013", "% d.% M.% Y"). Valid (); // Returns 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 occurred - wherever the value is not false:
// Returns ("year": - 5, "month": false, "day": false, "hours": false, // "minutes": false, "seconds": false, "milliseconds": false) tempus (). year (-5). // set the year \u003d -5, i.e. invalid errors (); // get the object with 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 desired format ("year", "month", "day", "hours", "minutes", "seconds", "milliseconds").
Here's a simple example of getting the number of months between November 1, 2013 and May 5, 2014:
// Returns 6 tempus (). Between (tempus (), "month");
Or how many hours are left until the new year
tempus (). between (tempus (), "hours");
In the last example, you can see that I only specified the year. When setting a value to an array or object, the missing values \u200b\u200bwill be
filled with the minimum. You can see the list of constants with minimum values \u200b\u200bin the documentation.

Also, we can change any date using the calc function:
// Returns a TempusDate with date 2012-01-01 tempus (). Calc ((year: 1, month: -4, day: -1));

Custom formats

We apply our own format for the month, which can take values \u200b\u200bfrom 1 to 12 (and not 01 to 12):
// Register a new format tempus.registerFormat ("% q", // directive -% q function (date) (// Here we specify the formatting function, i.e. what will be substituted for% q return date.month ();) , function (value) (// And here is the parsing function var v \u003d Number (value); return (month: (isNaN (v)? undefined: v));), 1, // The minimum length that the value 2 can take , // Maximum length "number" // Type); // Testing // Returns "01.1.2013"; tempus ((year: 2013, month: 1, day: 1)). format ("% d.% q.% Y"); // Returns ("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 a regular expression could be used. In fact, initially it was there, but after abandoning it, the speed increased several dozen times.
If you need to remove some format, then use unregisterFormat:
tempus.unregisterFormat ("% d"); // Returns "% d.01.2013", because directive% d no longer exists. tempus.format ((year: 2013, month: 1, day: 1), "% d.% m.% Y");

Getters / Setters

You can get / set some values \u200b\u200busing the functions year (), month (), day (), hours (), minutes (), seconds (), milliseconds (), dayOfWeek (), utc (), timestamp () or set (). For instance:
tempus (). // Get the current date year (1900). // Leave it as it is, but set it to 1900 leapYear (); // Check if it's a leap year, in this case false tempus (). Year (); // And this is how we get the current year in numerical form

Generating dates

You can generate a date in many ways, the full list of parameters is in the documentation. Here's a minimal example.
// returns ["03/29/2013", "03/30/2013", "03/31/2013", "04/01/2013", "04/02/2013"]; tempus.generate ((dateFrom: "20130329", formatFrom: "% Y.% m.% d", dateTo: "20130402", period: (day: 1), format: "% d.% m.% Y" ));
This can be useful for displaying charts by date and changing the display format directly on the client, without requests to the backend. The date can be generated either as an array or as objects, where the dates themselves will be the keys (this is useful when we need to bind an event to a date, for example, when we make our own calendar). Also, dates can be grouped by day, week, month, hour, year - whatever. This can also be applied to the calendar.

Plugins

And last but not least, 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's an example plugin:
(function (tempus) (var TempusDate \u003d tempus.classes ("TempusDate"); tempus.randomDate \u003d function () (var date \u003d 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); // Now we can create dates as follows var someRandomDate \u003d tempus.randomDate ();
I think that in this way it will be possible to conveniently write widgets using a bunch of jQuery + Tempus, Angular + Tempus, etc.

Source codes

You can install by downloading the sources from the github:
https://github.com/crusat/tempus-js/releases
Or via 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 know what is missing in it in order to further develop the library in the right direction. Thank you for attention!
P.S. Thanks for the invite!

Use new Date () to create a new Date object containing the current date and time.

note that Date () callable with no arguments, is equivalent to new Date (Date.now ()) .

Once you have a date object, you can use any of several available methods to retrieve its properties (for example, getFullYear () to get a 4-digit year).

Following are some common date methods.

Get the current year

var year \u003d (new Date ()). getFullYear (); console.log (year); // Sample output: 2016

Get the current month

var month \u003d (new Date ()). getMonth (); console.log (month); // Sample output: 0

Note that 0 \u003d January. This is because the months range from 0 before 11 so it is often desirable to add +1 to the index.

Get the current day

var day \u003d (new Date ()). getDate (); console.log (day); // Sample output: 31

Get the current hour

var hours \u003d (new Date ()). getHours (); console.log (hours); // Sample output: 10

Get current minutes

var minutes \u003d (new Date ()). getMinutes (); console.log (minutes); // Sample output: 39

Get current seconds

var seconds \u003d (new Date ()). getSeconds (); console.log (second); // Sample output: 48

Get the current milliseconds

To get the milliseconds (0 to 999) of an instance of a Date object, use the getMilliseconds method.

Var milliseconds \u003d (new Date ()). GetMilliseconds (); console.log (milliseconds); // Output: milliseconds right now

Convert the current time and date to a human-readable string

var now \u003d new Date (); // convert date to a string in UTC timezone format: console.log (now.toUTCString ()); // Output: Wed, 21 Jun 2017 09:13:01 GMT

The static Date.now () method returns the number of milliseconds since January 1, 1970 00:00:00 UTC. To get the number of milliseconds since that time using a Date object instance, use its getTime method.

// get milliseconds using static method now of Date console.log (Date.now ()); // get milliseconds using method getTime of Date instance console.log ((new Date ()). getTime ());