Contacts

JavaScript time in milliseconds. JavaScript get the current time and date. Methods for obtaining individual components of the DATE object

Date and time are part of our daily life and therefore occupy a prominent place in programming. In JavaScript, when creating a website, you may need to add a calendar, train schedule or interface to plan meetings. These applications must show the appropriate points of time depending on the current time zone of the user or perform calculations related to the arrival and departure of the aircraft or the start and end time of any event. In addition, you may need to use JavaScript to send daily reports at a certain time or for filtering (for example, to search for open-time restaurants).

Object Date.

Date is the built-in JavaScript object, which stores the date and time. It provides a number of built-in methods for formatting and managing these data.

By default, the new DATE instance without arguments creates an object with the current date and time in accordance with the system settings of the current computer.

For example, try to assign the current date variable. Create a file now.js.

// Set Variable to Current Date and Time
Const Now \u003d new date ();
// View The Output
now;
WED OCT 18 2017 12:41:34 GMT + 0000 (UTC)

The output is a string with the date that contains the following data:

Date and time are broken and displayed convenient for perception.

However, JavaScript perceives the date based on the timestrate of UNIX-time, which is a value consisting of the number of milliseconds that have passed since midnight on January 1, 1970. You can get a time stamp using the GetTime () method.

// Get The Current TimeStamp
now.gettime ();
1508330494000

A large number that appears in the output as a current timestamp is the number of milliseconds that have passed since midnight on January 1, 1970 on October 18, 2017.

Zero time (or EPOCH TIME) is represented by the date line 01 January, 1970 00:00:00 Universal Time (UTC) and a timestamp 0. You can check it in the browser by creating a new variable in the Epoch.js file and assigning it a new DATE instance. based on the time stamp 0.

// Assign The TimeStamp 0 to a New Variable
Const Epochtime \u003d New Date (0);
Epochtime;
01 January, 1970 00:00:00 Universal Time (UTC)

Zero time was selected as a standard for measuring time with computers, and this method is used in JavaScript. It is important to understand temporary tags and rows of dates, since these concepts can be used depending on the settings and objectives of the application.

Now you know how to create a new DATE instance based on the current time and based on time tag. A total of four DATE formats in JavaScript. In addition to the current time, the default and temporary label can also be used a dates string or specify a specific date and time.

To demonstrate various ways of links to a specific date, try creating new Date objects, which will be represented on July 4, 1776, 12:30 in Greenwich in three different ways.

// TimeStamp Method
NEW DATE (-6106015800000);
// Date String Method
NEW DATE ("January 31 1980 12:30");
// Date and Time Method
NEW DATE (1776, 6, 4, 12, 30, 0, 0, 0);

All these examples represent the same information about the date and time in three different ways.

As you can see, the temporary label method has a negative number; Any date to zero time will be presented as a negative number.

In the third example of a second and milliseconds are 0. If you do not have enough data when creating the DATE object, you must assign them 0. The missing data cannot be skidd out, since the time of time data in the string does not change. It should also be noted that the month of July here is indicated as 6, and not as 7. This is because the counting starts not from 1, but from 0. More about it - in the next section.

Removing the date using Get

Having a date, you can access all its components using various built-in methods. Methods return each part of the date relative to the local time zone. Each of these methods begins with GET and returns a relative number. Below is a detailed table of GET methods for the DATE object.

Date Time Method Range Example
Year getfullyear () Yyyy. 1970
Month getmonth () 0-11 0 \u003d January.
Day of the month getdate () 1-31 1 \u003d 1st of the Month
Day of the week getDay () 0-6 0 \u003d Sunday.
Hour gethours () 0-23 0 \u003d Midnight
Minute getminutes () 0-59
Second getSeconds () 0-59
Millisecond getmilliseconds () 0-999
Temporary label getTime ()

// Initialize A New Birthday Instance
Const Birthday \u003d New Date (1980, 6, 31);

Now you can use all methods to extract each date component.

birthday.getFullyear (); // 1980.
Birthday.getmonth (); // 6.
Birthday.getDate (); // 31.
Birthday.getday (); // four
Birthday.Gethours (); // 0.
Birthday.getminutes (); // 0.
Birthday.getSeconds (); // 0.
Birthday.getmilliseconds (); // 0.
Birthday.gettime (); // 333849600000 (for GMT)

Sometimes it is necessary to extract only part of the date, and the built-in GET methods will help you with it.

For example, you can compare the current date with the date on October 3 to find out, October 3 now or not.

// Get Today "S Date
Const Today \u003d New Date ();
// Compare Today with October 3rd
If (today.getdate () \u003d\u003d\u003d 3 && today.getmonth () \u003d\u003d\u003d 9) (
Console.log ("IT" S October 3rd. ");
) ELSE (
Console.log ("IT" S not October 3rd. ");
}
IT "S not October 3rd.

Built-in GET methods allow access to the date components.

Changing the date with Set

For all GET methods listed above, there is an appropriate SET method. If the GET is used to extract a specific date component, SET is used to change these components. Below is a detailed table of SET methods for the DATE object.

Date Time Method Range Example
Year setfullyear () Yyyy. 1970
Month setmonth () 0-11 0 \u003d January.
Day of the month sETDATE () 1-31 1 \u003d 1st of the Month
Day of the week sETDAY () 0-6 0 \u003d Sunday.
Hour sETHOURS () 0-23 0 \u003d Midnight
Minute setminutes () 0-59
Second setseconds () 0-59
Millisecond setmilliseconds () 0-999
Temporary label settime () Number of milliseconds from zero time

These SET methods can be used to change one or more date components. For example, you can change the year in the BIRTHDAY variable for 1997.

// Change Year of Birthday Date
Birthday.setFullyear (1997);
Birthday;
Thu Jul 31 1997 00:00:00 GMT + 0000 (UTC)

Now when calling a variable Birthday you see not 1980, and 1997.

Built-in SET methods allow you to change different parts of the DATE object.

UTC Methods

The GET methods described above retrieves the date components based on the local user zone settings. To increase the control over dates and time, you can use the GETUTC methods that work in the same way as GET methods, but calculate the time based on the UTC standard (worldwide coordinated time). Below is the UTC method table for the Date object in JavaScript.

Date Time Method Range Example
Year getutcfullyear () Yyyy. 1970
Month getutcmonth () 0-11 0 \u003d January.
Day of the month getutcdate () 1-31 1 \u003d 1st of the Month
Day of the week getutcday () 0-6 0 \u003d Sunday.
Hour getutchours () 0-23 0 \u003d Midnight
Minute getutcminutes () 0-59
Second getutcseconds () 0-59
Millisecond getutcmilliseconds () 0-999

To check the difference between the local GET methods and the Get UTC methods, start the following code.

// Assign Current Time To a Variable
Const Now \u003d new date ();
// PRINT LOCAL AND UTC TIMEZONES
Console.log (now.Gethours ());
Console.log (now.getutchours ());

This code will display the current time and time on the UTC time zone. If you are now in the UTC time zone, the numbers that the program will withdraw will be the same.

UTC provides an international time standard and therefore can support code in accordance with time zones if necessary in your program.

Conclusion

In this manual, you learned how to create an instance of the Date object, how to use its built-in methods for accessing and changing the components of a specific date. More information about the time and date in JavaScript you can find on Mozilla Developer Network.

The ability to work with dates is important for many common tasks in JavaScript: from creating regular reports before displaying dates and schedules in the correct time zone.

Tags:

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)). 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. December 7, 2014 at 12:30

Date and time problems in js

  • Javascript.

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.

Another useful thing for sites is the insertion of the current date. Examples of dates scripts can be found on the Internet dozens, but many of them, in my opinion, are heavy and, therefore, ugly. Meanwhile using standard tools Javascript., Insert the date on the site page can be very simple. I often apply it! In the picture (screenshot from the operating site) manor "Fairy Tale" !

Here is the whole date script:

In my opinion, it's easier to nowhere, quite beautiful and understandable. If you do not have any desire to study the construction of this script, then simply insert it into any place of the HTML page and get the following inscription:

One more option more advanced


! Today

He looks like this:

Today

In general, no skills are required, just stupidly insert the code and everything is OK!

Read more:

So, start with the assignment of the date value of the variable d., then create arrays ( Array.) for the days of the week ( day.) and months ( mONTH.), indicating them in the necessary grammatical form: the case, the number, the title letter, if the word is at the beginning of the date, etc. The last line of the script is actually printing the date ( document.Write.). Here you install that in which sequence will be displayed in the line of the current date. Components are separated from each other. + . Construction is used to enter a space " " , and for entering the letter G (year) - design "G."

As can be seen from the script, receiving data about current time performs the element get.. This method allows you to get the following information:

  • getdate () - Returns the number from 1 to 31, representing the number of months;
  • getDay () - Returns the day of the week as an integer from 0 (Sunday) to 6 (Saturday);
  • getmonth () - Returns the number of months a year;
  • getfullyear () - Returns the year. If using simple getYear ()then the current year will be output minus 1900;
  • get Hours () - Returns an hour of day;
  • getminutes () - Returns moments as a number from 0 to 59;
  • getSeconds () - Returns the number of seconds from 0 to 59.

Insert directly Java.Script inside the site site is not always convenient. It is better to put a description of the script to the top of the page between the tags And set the variable that we will call as needed in the text. Let's call it Today. And we define the output form in it similarly to the foregoing. The script will look like this:

To display the date, call the script in the right place of the HTML page of the page using the following command:

If your site contains many pages on which you want to show the date, it is more convenient to allocate Java.script output dates in a separate file, for example, data.js.. Practically, this is a page consisting of the first of the described scripts, that is, with a string document.Write. (see above). It is necessary to have it in the same directory as the main page, and cause the date at the output place as follows:

Do not forget to check the file data.js. He had the same encoding as the main document, otherwise the date will be removed with wonderful hooks, squares and other fintyphushki.

Comment. It should be borne in mind that the described script displays the date set on the user's computer, which does not always correspond to the real current time. If you need to show exact time, you must use the PNP script that will show time on the server.

Get the current date in JavaScript is very simple. For this purpose, the DATE object is intended. Its syntax is quite simple, and the names of the methods intuitively understandable. In the examples below, I will show how to work with the DATE object ( JavaScript New Date.) To get current year, month, day and time with an accuracy of millisecond!

Receiving current date:

To get the current date in JavaScript, use the new keyword to create a new instance of the DATE object.

var date \u003d new date (); Console.log (Date);

This code displays the following information to the console:

// Tue Feb 02 2016 15:46:56 GMT-0500 (Eastern Standard Time)

It displays the current day of the week, the current month, day of month, year and even the current time in 24-hour format. Fragment " GMT."Means Greenwich time, and" -0500 "This is the difference in time zones between local time and GMT.

Quote from Wikipedia: "Greenwich's average time ( GMT.) - This is a secondary sunny time in the Royal Observatory in Greenwich, London. " It's connected with universal coordinated time (UTC.). « Eastern Standard Time."In the displayed date, refers to the time zone of your browser or computer.

* Please note that GMT and UTC differ in each other. We will consider UTC values \u200b\u200bin minutes.

* Also note that the date in JavaScript is determined by time in milliseconds, which has passed since midnight, January 1, 1970, UTC. In one day 86,400,000 milliseconds. The range of the DATE object is from -100,000,000 days to 100,000,000 days relative to January 1, 1970, UTC.

* The values \u200b\u200bobtained using the method mentioned above are dependent on the system settings of your device. If you change the computer clock settings, the time that will return this method will change.

Well, we dealt with New Date JavaScript formats and are now ready to move on!

Getting a day of the week:

To get the day of the week, use the method JavaScript object DATE GetDay ():

var day \u003d date.getday (); Console.log (Day);

* Please note that the days of the week are numbered from 0 to 6, Sunday \u003d 0, Monday \u003d 1, Tuesday \u003d 2 and so on.

Getting a month:

To get the current month of this year, use the getmonth () method. Before that, I said that the names of the methods intuitively understand!

var MONTH \u003d date.getmonth (); Console.log (Month); //one

* Please note that, like the days of the week, months are returned in a numeric format from 0 to 11; January \u003d 0, February \u003d 1, March \u003d 2 and so on.

Getting a day of the month:

To get the day of the month, you can use the GetDate () method.

var dayofmonth \u003d date.getdate (); Console.log (Dayofmonth); // 2.

* GETDATE () method returns the days of the month, numbered from 1 to 31; Number 1 corresponds to the first day of the month.

Getting time:

To get the current time, the GetTime () method is used.

var time \u003d date.gettime (); Console.log (Time); // 1454461242058.

Looks ... Strange ... What is it? You see the number of milliseconds that have passed since January 1, 1970 00:00:00 UTC. So how old is it?

1454461242058 MS / 31540000000 ms per year \u003d about 46 years
1970 + 46 years old \u003d 2016

Let's check to make sure:

var year \u003d date.getfullyear (); Console.log (YEAR) // 2016

Yes that's it! We have just brought the current date and time using the JavaScript New Date.



Did you like the article? Share it