Output time and dates in JavaScript. JavaScript get the current time and date. Get current hour

Hello everyone!
I often have to work with statistical data and there is very much tied up on dates. Moreover, one and the same date can be used on a page in different formats (for example, in a convenient machine and in a convenient person). I think most of you perfectly represent all this terrifying code that is obtained when using the DATE object.
For example, to get the current date in DD.MM.YGYY format. We will need to do the following:
var d \u003d new date (), fd \u003d d.getdate () + "." + (d.getmonth () + 1) + "." + d.getfullyear ();
And when such strings become a lot? Is it easy to mention that in JavaScript a month starts from scratch when you develop not only on it? Or what is there milliseconds, and not a second, how almost everywhere on the backend? You can solve part of the tasks of the popular library Moment.js, but it works very slowly.
The library under consideration solves these problems.
If I wonder, I suggest you read this little review.

TEMPUSJS largely consists of syntax sugar over the DATE object, so it works very quickly. The syntax of the library itself is very simple. For example, write the previous example, you can:
var fd \u003d tempus (). Format ("% d.% m.% y");
Now about speed. In the spoiler you can see the TEMPUS comparison with the Moment and the native date formatting method (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 sample) Moment x 284,864 OPS / SEC ± 0.85% (96 Runs sample) TEMPUS X 2,086,081 OPS / SEC ± 0.73% (97 Runs Sample)
Formatting
Native JS X 1,637,517 OPS / SEC ± 0.61% (100 Runs sample) Moment x 8,808 OPS / SEC ± 1.07% (100 Runs sample) TEMPUS X 942,815 OPS / SEC ± 0.68% (94 Runs sample)
Auto Detection of Date and Parsing
Native JS x 11,204,316 OPS / SEC ± 0.81% (88 Runs sample) Moment x 38,511 OPS / SEC ± 1.41% (95 Runs sample) Tempus x 93,973 OPS / SEC ± 1.06% (85 Runs sample)
PARSING DATE ON Format
Moment x 46,293 OPS / SEC ± 0.63% (100 Runs sample) Tempus x 109,947 OPS / SEC ± 0.93% (99 Runs sample)
Parsing and validation
Moment x 44,588 OPS / SEC ± 1.09% (90 Runs sample) Tempus x 103,439 OPS / SEC ± 0.90% (94 Runs sample)
The results were obtained on my laptop in Google Chrome 30.0.1599.114. In other browsers, the results differ, but the ratio remains about the same.
For tests used library BENCHMARK.JS
Benchmark on other functions, you can see.

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

  • Supports IE6 +, Chrome, Firefox, Opera;
  • Supports chains of calls;
  • Months can begin with 1 (default), not zero;
  • Milliseconds can be disabled (by default) or included;
  • Fast work (as, in many cases, the Date object is used native to browser, the implementation of which is written in faster languages);
  • Supports custom formats and plugins
  • The validation of the date is very fast and depends only on the setting date of the functions (because validation is already under the enhancing values, and not calculated separately);
  • Multilingual and auto definition of the user language.

Here it will be only about some functions.

Formatting and parcel

So, for starters another example of the date formatting. Here we also use chain challenges. At the end of each setting, we get a TEMPUSDATE object, which can be used further in the chain. Example:
Tempus (). // Get a new date CALC ((MONTH: -1)). // Reduce it for one month Format ("% d.% m.% y"); // Display in the form of a string
Thus, we will get the same day, an hour and a second, but a month ago. This is useful for reports for the last month.

The following example is the dates parceling.
// return the object TempusDATes date "2013-11-18" TEMPUS ("18.11.2013"); // return the object tempusdate with the date "2013-12-12" tempus ("2013-12-12", "% y-% m-% d"));
Tempus can automatically determine some known formats. Also, you can specify a specific format, then the parcel will occur faster. Plus, you can specify the date that will be returned if the parsing fails:
// T.K. "123" does not suit the format "% d.% M.% Y", then // The object containing the date 2013-01-01 TEMPUS will be returned ("123", "% d.% M.% Y", TEMPUS ());
List of formats by default can be viewed.

And now 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 language will be selected (take from the browser) or default language if the user language is not detected among the available TEMPUS languages.
// Install the TEMPUS.Lang language ("RU"); // Standardly use Format // "November, 05" Tempus (1383609600) .Format ("% b,% d");
At the moment, languages \u200b\u200bare only two - Russian and English, so I will be glad to help.

Validation

Date validation occurs as follows:
// Return False Tempus ("32.08.2013", "% d.% M.% Y"). Valid (); // Retain True Tempus ("00:00 01.01.2012", "% h:% m% d.% M.% Y"). Valid ();

In case of error, you can see the fields in which it originated - everywhere where the value is not false:
// Return ("YEAR": - 5, "MONTH": FALSE, "DAY": FALSE, "Hours": false, // "Minutes": false, "Seconds": false, "MilliseConds": False) Tempus (). Year (-5). // Set the year \u003d -5, i.e. Nevalid Errors (); // Get an object with errors

Dat 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 is a simple example of obtaining the number of months between November 1, 2013 and May 5, 2014:
// will return 6 tempus (). Between (Tempus (), "Month");
Or how many hours left before the new year
Tempus (). Between (Tempus (), "Hours");
In the last example, you can see that I only pointed the year. When setting the value with an array or object, lack of values \u200b\u200bwill be
filled with minimal. List of constants with minimal values, you can see in the documentation.

Also, we can change any date using the CALC function:
// return tempusdate with the date 2012-01-01 tempus (). Calc ((year: 1, month: -4, day: -1));

His formats

We use your format for a month, which can take values \u200b\u200bfrom 1 to 12 (and not 01 to 12):
// We register a new format tempus.registerformat ("% q", // Directive -% q FUNCTION (DATE) (// Indicate the formatting function, i.e. what will be substituted instead of% q return date.month ();) , FUNCTION (VALUE) (// And here the VAR V \u003d Number parsing function; RETURN (MONTH: (ISNAN (V)? undefined: v));), 1, // Minimum length, which is 2 , // Maximum length "Number" // Type); // Test // returns "01.1.2013"; Tempus ((Year: 2013, MONTH: 1, Day: 1)). Format ("% d.% Q.% y"); // Retain ("YEAR": 2013, "MONTH": 2, "DAY": 10, "Hours": 0, "Minutes": 0, "Seconds": 0); Tempus ("10.2.2013", "% d.% Q.% y"). Get ();
When registering, you can see that some parameters are specified separately, while the regular expression could be used. In fact, it was originally it was, but after the refusal of it, the speed rose a few dozen times.
If you need to delete some format, use unregisterformat:
TEMPUS.UNREGISTERFORMAT ("% D"); // Return "% D.01.2013", because Directive% D no longer exist. Tempus.Format ((Year: 2013, MONTH: 1, Day: 1), "% d.% m.% y");

Getter / Setters

You can receive / set some values \u200b\u200busing the functions of the year (), month (), day (), hosts (), minutes (), seconds (), milliseconds (), dayofweek (), utc (), timestamp () or set (). For example:
Tempus (). // Get the current date Year (1900). // leave everything as it is, but we install 1900 Leapyear (); // Checking whether this year is a year, in this case False Tempus (). Year (); // And so we get the current year in the numerical form

Generation Dat.

You can generate a date with a multitude of ways, a complete list of parameters is in the documentation. Here is a minimum 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" ));
It can be useful for displaying graphs by date and change the display format directly on the client, without requests to the backend. The date can be generated as an array, as well as objects where the dates themselves are as keys (this is useful when we need to bind any event to any date, for example, when we make your calendar). Also, dates can be grouped by day, weeks, months, hours, years - for anything. It can also be applied to the calendar.

Plugins

Well, the last - plugins. Here we extend the factory to generate a random date. Also, we will need a TempusDate class, it can be found in tempus.classes (). Here is an example of a plugin:
(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_monteh)) + tempus.min_month)). Day (Math. Floor ((Math.Random () * (date.daycount () - tempus.min_day)) + tempus.min_day)). Hours (Math.floor ((Math.Random () * (tempus.main_hours - Tempus.min_hours) ) + Tempus.min_hours)). Minutes (Math.floor ((Math.Random () * (tempus.main_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 the dates as follows VAR SomeRandomDate \u003d Tempus.randomDate ();
I think that in this way it will be convenient to write widgets using a jQuery + TEMPUS, Angular + Tempus, and the like.

Sources

You can install by downloading the sources from Githab:
https://github.com/crusat/tempus-js/releases.
Or through Bower:
$ Bower Install Tempus
You will need only one file - tempus.js or tempus.min.js.

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

In this lesson, we will get acquainted with the DATE object of the JavaScript language and learn how to use it in practice.

Creating a date - 4 examples

In JavaScript, the creation of the date is carried out using the DATE object. The DATE object is a point on the time axis and is designed to store the date and time with an accuracy of milliseconds.

Examples of dates in JavaScript.

1. Creating the current date and time.

Get the current date and time in JavaScript is carried out by creating an instance of the DATE object without specifying parameters:

// current date (date and time that was at the time of creating an instance of the DATE object on the local computer user) var now \u003d new date (); // For example, withdraw the current date in the console Console.log (NOW);

If you need to get only today in the string format, you can use the TolocaledateString method:

Var now \u003d new date (). Tolocaledatestring (); // 12/19/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 the string format can be obtained as follows:

Var Now \u003d New Date (). Tolocalestring (); // 12/19/2019, 11:02:48

2. Creating a date by specifying the DATE object of the number of milliseconds that have passed since January 1, 1970 00:00:00 UTC.

// 1 year (not high) \u003d 365 * 24 * 60 * 60 * 1000 \u003d 31536000000 ms // For example, create a date 01/01/1971, 00:00:00 on UTC: var date1 \u003d new date (31536000000);

3. Creating a date by specifying its DATE object as a string.

At the same time, the JavaScript date creation will try to understand the string transmitted to it and form it on the basis of its date. The row conversion in the date in JavaScript is carried out using the Date.Parse method.

For example:

// Creating a date based on a string in DD.mm.yy var Date1 \u003d New Date format ("05.11.19"); // Create a date based on a string in YYYY-MM-DDTHH: MM: SS.SSS (symbol T used to split the date and time) var Date2 \u003d New Date ("2015-02-24T21: 23"); // Create a date on the basis of a string with an indication of the time zone (yyyy-mm-ddthh format: 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 through the comma: Year (4 digits), month (the countdown is conducted from 0), day (1..31), hours (0..23), minutes (0..59), seconds (0..59), milliseconds (0. .999). Moreover, only the first two parameters are mandatory.

An example of creating a date indicating only mandatory parameters:

// Create a date 01.01.2015 (unspecified default parameters are equal: Number - 01, hours - 00, minutes - 00, seconds - 00, milliseconds - 000). VAR DATE1 \u003d New Date (2015.01); // Create a date 01/24/2015, 21:23 VAR DATE2 \u003d New Date (2015,0124,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 ()); // 2 Example var newdate \u003d new date (date.utc (2015,1,1)); alert (newdate.toutcstring ());

Obtaining individual components of the date and time

In JavaScript, the following methods are intended to obtain individual components of the date and time:

  • getfullyear () - returns a year consisting of 4 numbers;
  • getmonth () - Returns a month in the format of numbers from 0 to 11 (0 - January, 1 - February, 2 - March, ..., 11 - December);
  • getdate () - returns the number of months 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 amount of milliseconds from 0 to 999.

All these methods return separate components of the date and time in accordance with the time zone installed on the local device device.

// Create a date 11.11.2019 00:00 UTC VAR NewDate \u003d New Date (date.utc (2019,11,11)); // We obtain the Date Components, if the Local time device is equal to 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 welcome the user depending on which one is now the time interval:

// We obtain the current user and components of this time VAR NOW \u003d NEW DATE (), HOUR \u003d now.Gethours (), minute \u003d now.getminutes (), second \u003d now.getSeconds (), Message \u003d ""; // Determine the phrase of greetings depending on the local user 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 output in the desired format is carried out using a ternary operator.

JavaScript has analogues of these methods to obtain individual dates and time components for the UTC + 0 time zone. These methods are called similarly, but with the added "UTC" after "Get": getutcfullylar (), getutcmonh (), getutcdate (), getutchours (), getutcminutes (), getutcseconds (), getmilliseconds ().

You can get the day number 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 I translate the day of the week from a numeric in a string representation:

Var Days \u003d ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; // We obtain the current date var NOW \u003d new date (); // withdraw in the console day of the week Console.log ("Today" + Days);

You can get the number of milliseconds from 01/01/1970 00:00:00 UTC in JavaScript using the GetTime () method.

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

Installation of individual dates and time components

In JavaScript, you can install separate dates and time components using the following DATE object methods:

  • sETFULLYEAR (YEAR [, MONTH, DATE]) - installation of the year (you can additionally set another month and number);
  • sETMONTH (MONTH [, DATE]) - installation of 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) - set number;
  • sethours (Hour [, Min, Sec, MS]) - installs an hour from 0 to 23 (you can additionally install minutes, seconds and milliseconds);
  • setminutes (min [,) - sets the minutes from 0 to 59 (you can additionally install even seconds and milliseconds);
  • setseconds (SEC,) - Sets seconds from 0 to 59 (you can additionally install more milliseconds);
  • sETMILLISECONDS (MS) - sets milliseconds (from 0 to 999).

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

// Create an instance of the DATE object containing the current date var NewDate \u003d New Date (); // Set the year newdate.setfullyear (2019); // Set the year and month of NewDate.setFullyEar (2019, 08); // Set 20.09.2019 NewDate.setFullyear (2019, 08, 20); // Set the month of NewDate.SetMonth (05); // Set the month and number newdate.setmonth (05, 15); // Set the number NewDate.SetDate (28); // Install the NEWDATE.Sethours (13) hour; // install an hour and minutes newdate.sethours (13.20);

In JavaScript, setting the date and time in the UTC + 0 time zone is carried out using the following methods: setutcfullyear (), setutcmonth (), setutcdate (), setutchours (), setutcminutes (), setutcsecondes (), setutcmilliseconds ().

Setting the date and time using the number of milliseconds that have passed since 01/01/1970 00:00:00 UTC is carried out using and then settime ().

In addition, in JavaScript, the specification of incorrect components of the date and time does not lead to errors, they will simply be automatically distributed over the rest.

For example:

// Number 44 will be distributed as follows: 44 - 31 \u003d 13, February 13, 2019 NewDate.setFullyear (2019, 01, 44);

This technique can be used when you need to receive a date that differs from this time at a certain period of time.

// Date, which will be more newDate for 7 days NewDate.SetDate (Date1.getDate () + 7); // Date, which will be less than NewDate for 120 seconds NewDate.setSeconds (Date1.getSeconds () - 120); // So you can set the last number of the previous month for NewDate NewDate.SetDate (0);

Conversion of dates in the string and its formatting

In JavaScript, the methods that perform the date transformation in the string can be divided into 2 groups.

The first group includes the methods that perform this as defined in the browser: Tostring (), TODATESTRING (), TOTIMESTRING (), TUTCString ().

The Tostring () method returns the full date of the date, TODATESTRING () is only a date, TOTIMESTRING () - only time, toutcstring () is a complete date of date, but in the time zone UTC + 0.

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

To the second group You can attribute methods taking into account the time zone and a local computer language: TOLOCALESTRING () - date and time, tolocaledatestring () - only date, tolocaletimestring () - only time.

Tolocalestring () methods, tolocaledatestring (), TolocaletimeString () have 2 optional parameters. The first parameter is designed to explicitly specify the locale, the second - to specify the formatting options.

If the locale is clearly not installed or undefined, the browser takes the one that he has the default.

In addition, JavaScript has another toSostring () method. It returns a string containing the date and time in ISO format (YYYY-MM-DDTHH: MM: SS.SSSSZ).

// Create a 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 for converting a string at the date

JavaScript To convert the string to the date uses the Date.Parse () method. This method can convert a string if it is completed in accordance with RFC2822 or ISO 8601 standard.

In this lesson, consider the ISO 8601 standard, in which the string must have the following format: yyyy-mm-ddthh: mm: ss.ssssz.

  • Yyyy - a year consisting of 4 digits;
  • Mm - month consisting of 2 digits (01 \u003d January, 02 \u003d February, etc.);
  • DD - day of the month, consisting of 2 digits (01..31);
  • T - symbol for dividing the date and time;
  • hH - number of hours (00..23);
  • mM - number of minutes (00..59);
  • sS - number of seconds (00..59);
  • sSS - the number of milliseconds (0..999);
  • Z is a symbol that means that 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 + HH: mm or -hh.mm.

If the line containing the date and time is specified not in the RFC2822 or ISO 8601 format, then the JavaScript Date.Parse () method still can perform its conversion, but the result in this case may be unpredictable.

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

Who is guilty
The first problem occurs when you need to set the date / time in the time zone other than UTC and from local. The DATE designer does not have such a 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 the offset relative to the UTC - the third method. The constructor call in this format allows you to transfer the offset as part of the line:

New Date ("Sun Feb 01 1998 00:00:00 GMT + 0700")
The row is accepted in RFC2822 format, very uncomfortable and difficult to manually input. It is almost impossible to get such a string from the user input. I can not imagine a person who agreed to enter the date in such a format.

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

Offset relative to UTC is not a constant. This is a function of a date, time (well, or from Timesshampa, if you please) and, again, the time zone. For example, for Moscow, the last time transfer 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 designer in the third version becomes almost useless because the offset needs to be known in advance. And it, as it was said, so simply received to be. The only library, from I got, which uses the Olson database for the shifting of the shifts - TimeZone-JS. The problem of using this library is that underground libraries (Date / Time Picker-s) do not know anything and insistently use standard DATE inside. The remaining libraries working with the Date object is clearly not referring to this database and the updates do not receive from it. (Correct me in the comments.)

The business of the use of the time zone makes sense only if the date and time are specified. For example, if the working day begins at 9:00, it is unlikely that you expect that your colleague from Vladivostok will start working at 15:00. Timesons should not be taken into account and in this case you need to display the date in UTC. However, in the case of regular events occurring at one point in time in different time zones, the Timeson is still needed. For example, your daily scar begins 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 the time without offset, and GMT is the time with displacement 0. I will explain on the example:

12/31/2014, 20:59:59 GMT in the Moscow time zone should look like 12/31/2014, 23:59:59 12.12.2014, 20:59:59 UTC in the Moscow time zone should look like on 12/31/2014, 20:59 : 59.
Because of this arithmetic, they are mainly confused. Unfortunately, inhabited with this parameter everywhere. The lack of direct indication of the Timesone in JS is interpreted as a local timezone, and the instruction of UTC and GMT is equivalent.

In a situation, I could help Intl. Could, but not obliged. In particular, there is such a parameter TimeZone, but, a little further, the standard defines: The Time Zone to Use. The Only Value Implementations Must Recognize IS "UTC". Currently, in addition to Chrome, not one browser arbitrary timezones does not support.
With time bands in JS, everything is completely bad - there is nothing like that in the language. Want to do well - do myself.

What to do
  • Option 1.
    Do not use arbitrary Timson. The option is preferable and probably the most painless. That is, you have only local Timeson and UTC. For these cases in all browsers, it seems like everything is, albeit is not very convenient. In addition, the Timeson is set globally for the OS and change it for a specific Web application is notocherly.
  • Option 2.
    If arbitrary times are needed - not to use TimesTAMP. At all. Store time in the savings checkout in RFC string indicating the timezons. Not sure that this will help defeat the timer shifts in a cross-browser understanding, but, at least, Chrome about such shifts in the know.
  • Option 3.
    There are different situations and it happens that at the database time is recorded with any device. That is, in the form of TimesTampa. There is no place to run here that would correctly display time you need to know either a timeon of the device, or a thaimon of the user, or both of the other and to identify all the shifts in hand. Without using Olon's base, do not do here.
  • There must be a morality of this fable, but there is nothing more to add me. In the draft of the ECMA standard, I do not observe any progress, you will probably not.

The Date object allows you to work with dates and time. To create a new DATE object, uses the following syntax:

NEW DATE ()

Dates are stored in it as the number of milliseconds who have passed since midnight January 1, 1970 according to the Universal World Time (UTC). Thanks to this format using Date, it is possible to accurately represent dates, within 1 January 1970 at 285616 years.

If the Date Designer is called without arguments, an object with current date and time values \u200b\u200bis created. To create a DATE object with a specific date or time, you will need to transfer one of the four possible parameters:

  • milliseconds: the value should be a number of milliseconds from 01/01/1970 VAR Birthdate \u003d New Date (8298400000); Document.Write (Birthdate);
  • row with date: Any date in the format supported by PARSE () var Birthdate \u003d New Date ("April 16, 1975"); Document.Write (Birthdate);
  • year, month, day var birthdate \u003d new date (1975, 4, 28); Document.Write (Birthdate);

    Please note that the number 4 corresponds to May month. This means that January corresponds to the number 0. Similarly, the days are calculated, only zero in this case corresponds to Sunday.

  • year, month, day, hour, moments, seconds, milliseconds

When working with the DATE object, it is important to remember that the calculations are performed using a single worldwide time (UTC), despite the fact that your computer can display time according to your time zone.

Methods

MethodDescription
getdate ()Returns the day of the month (from 1 to 31) for the specified date local time.
getDay ()Returns the day of the week (from 0 to 6; 0 \u003d Sunday, 1 \u003d Monday, etc.) for the specified date local time ..
getfullyear ()Returns the year (four digits).
gethours ()Returns an hour (from 0 to 23).
getmilliseconds ()Returns milliseconds (from 0 to 999).
getminutes ()Returns moments (from 0 to 59).
getmonth ()Returns a month (from 0 to 11; 0 \u003d January, 1 \u003d February, etc.).
getSeconds ()Returns seconds (from 0 to 59).
getTime ()Returns the number of milliseconds that have passed since midnight 01/01/1970.
getTimeZoneoffset ()Returns time difference between UTC time and local time, in minutes.
getutcdate ()Returns the day of the month for world time (from 1 to 31).
getutcday ()Returns the day of the week for world time (from 0 to 6).
getutcfullyear ()Returns the year for world time (four digits).
getutchours ()Returns an hour for world time (from 0 to 23).
getutcmilliseconds ()Returns milliseconds for global time (from 0 to 999).
getutcminutes ()Returns moments for world time (from 0 to 59).
getutcmonth ()Returns a month for global time (from 0 to 11).
getutcseconds ()Returns seconds for world time (from 0 to 59).
parse ()Analyzes the dates string (for example, "May 21, 1992") and returns a line with a date value that contains a number in milliseconds from January 1, 1970 00:00:00.
sETDATE ()Sets the day of the month for the specified date local time (from 1 to 31).
setfullyear ()Sets the year (four digits).
sETHOURS ()Sets the clock for the specified date local time (from 0 to 23).
setmilliseconds ()Sets milliseconds for the specified local time date.
setminutes ()Sets moments (from 0 to 59).
setmonth ()Sets the month (from 0 to 11).
setseconds ()Sets seconds (from 0 to 59).
settime ()Sets the date in milliseconds after (or before) 01/01/1970.
setUTCDATE ()Specifies the day of the month.
setutcfullyear ()Sets the year for world time (four digits).
setutchours ()Sets an hour for the specified date on the World Time.
setutcmilliseconds ()Specifies milliseconds for the specified date on the World Time.
setutcminutes ()Sets moments for the specified date on the World Time.
setUTCMONTH ()Specifies a month for the specified date on the World Time.
setutcseconds ()Sets seconds for the specified date on the World Time.
tODATESTRING ()
toSostring ()Converts date to the string using the ISO 8601 standard.
tojson ()Returns the date as a string formatted as the JSON date.
tolocaledateString ()
tolocaletimeString ()Returns a part of the date as a string, with the date representation based on the system parameters.
tOLOCALESTRING ()Returns the date in the form of a string, with the date representation based on the system parameters.
tostring ()Returns a string representing the specified DATE object.
totimeString ()Returns part of the date as a string.
tuTCString ()Converts the date in the string using the UTC time zone.
UTC ()Takes the same parameters as the long form of the constructor (i.e. 2-7) and returns the number of milliseconds from January 1, 1970, 00:00:00 UTC.
valueof ()Returns the primitive value of the DATE object.

JavaScript - Lesson 11. Date, performance and processing

In JavaScript, the date is determined by the amount of milliseconds that have passed since January 1, 1970.

Built-in object is used to work with the date and time. Date.. This object does not have properties, but has several methods that allow you to install and change the date and time.

An object Date. Created using the operator new and designer - Date..

For example:

var Mydata \u003d New Date ();

Variable value myData. There will be a current date and time:

Methods of the object Date. You can receive separateness of the month, day of the week, hours, minutes and seconds:

  • getdate. - Returns a number in the range from 1 to 31, representing the number of months.
  • gethours. - Returns an hour of day in the range from 0 (midnight) to 23.
  • getminutes. - Returns moments in the range from 0 to 59.
  • getSeconds. - Returns seconds in the range from 0 to 59.
Suppose we want to write a script that will determine the current time and withdraw it in the "CC: MM: SS: SS format."

JavaScript Date

Now write the function itself nTIME ():

function NTIME (OBJ) (var t \u003d new date (); var h \u003d t.gethours (); var m \u003d t.getminutes (); var s \u003d t.getseconds (); var left \u003d h + ":" + m + ":" + S; Obj.res.Value \u003d Result;)

* How do you remember the methods are separated from the object point, we talked about this in a lesson 3 * As you can see, everything is simple. First, we determine the current time, and then with the help of methods, remove the individual values \u200b\u200bof the clock, minutes and seconds from it.

Here you still want to explain the string var Result \u003d H + ":" + M + ":" + s. For the first time we have encountered the need to dismiss as variable values \u200b\u200band simple text. In principle, nothing complicated: variables are written as it is, the text is taken in quotes, and the sign + Conducts the operation of concatenation, i.e. Their associations.

In our example, one defects remained, we wanted to be displayed in the format "CC: MM: SS", and now it is displayed in the format "H: M: C". Those., At 5 am, the time will be displayed as "5: 0: 0", and I would like this: "05:00:00" (which is more familiar). As a home job you can try to fix it. For example, using the operator if. and the string literal "0" (the idea is simple: if the clock is less than 10, then in the result before h. Write "0" and so with all variables).

In the meantime, continue to study the objects of the object Date.:

  • getDay. - Returns the day of the week as an integer from 0 (Sunday) to 6 (Saturday).
  • getMonth. - Returns the number of months a year, as an integer from 0 (January) to 11 (December).
  • getYear. - Returns the year in the form of the last two numbers ( getfullyear. - Returns the year in the form of four digits).

    * Unfortunately, since 2000, there is a problem with the display of the year in different browsers. The GetYear method in IE displays a full year (instead of the last two digits), and Firefox instead of XX displays 1xx (i.e. substrates 1). Therefore, it is preferable to use the GetFullyear method.

Let's write a script that will determine the current date and display it in the "number of the year" format.

HTML page code will be simple:

JavaScript Date

Now write the function itself tDATA ():

Function TDATA (OBJ) (VAR S; var t \u003d new date (); var y \u003d t.getfullyear (); var d \u003d t.getdate (); var mon \u003d t.getmonth (); switch (MON) (Case 0: s \u003d "January"; Break; Case 1: S \u003d "February"; Break; Case 2: S \u003d "March"; break; Case 3: S \u003d "April"; Break; Case 4: S \u003d "May "Break; Case 5: S \u003d" June "; Break; Case 6: S \u003d" July "; Break; Case 7: S \u003d" August "; Break; Case 8: s \u003d" September "; Break; Case 9 : s \u003d "October"; Break; Case 10: s \u003d "November"; Break; Case 11: s \u003d "December"; Break;) Var Result \u003d D + "" + s + "" + y; obj.res.value \u003d result;)

It turned out more authentic than in the first example, because You have to translate the name of the names of months to Russian.

The methods discussed above allow you to receive a date. If we need to set the date, then the following methods should be used:

  • setDate. - Sets the number of month in the range from 1 to 31.
  • sethours. - Sets an hour for the current time ranging from 0 (midnight) to 23.
  • setminutes. - Sets moments in the range from 0 to 59.
  • setSeconds. - Sets seconds in the range from 0 to 59.
  • sETYEAR - Sets the value of the year.
  • setmont - Sets the value of the month in the range from 0 (January) to 11 (December).
  • setTime. - sets the value of the object Date. And returns the number of milliseconds that have passed since January 1, 1970.
So, if we need to set the date of December 06, 2010, we will have the following code in the function:

Var t \u003d new date (); VAR Y \u003d T.Setyear (2010); VAR D \u003d T.SetDate (6); var mon \u003d t.setmonth (11); ...

You can set the date directly in the designer by specifying as a parameter of the format line "month, day, a year watch: minutes: seconds":

VAR T \u003d New Date ("Feb, 10,1975 17:45:10");

The value of the clock, minutes and seconds can be omitted (they will be zero):

Var t \u003d new date ("Feb, 10,1975");

The same date can be set using numbers by listed through the comma, month, number, hours, minutes, seconds:

Var t \u003d new date (75, 1, 10, 17, 45, 10);

Or, lowering hours, minutes and seconds (they will be zero):

Var t \u003d new date (75, 1, 10);

* There is a problem: IE does not want to display, so it's better not to use these options.

Here, and everything, you are quite ready to independently write a script, which when loading the page will display the date, time and day of its visit (in normal Russian). Good luck!