Javascript current time in milliseconds. JavaScript Get current time and date

The Date object allows you to work with dates and times. The following syntax is used to create a new Date object:

New Date ()

It stores dates as the number of milliseconds since midnight, January 1, 1970, according to universal time (UTC). With this format, Date can accurately represent dates that are 285616 years from January 1, 1970.

If the Date constructor is called with no arguments, an object is created with the current date and time values. To create a Date object with a specific date or time, you will need to pass one of four possible parameters:

  • milliseconds: the value must be the number of milliseconds since 01.01.1970 var birthDate = new Date (8298400000); document.write (birthDate);
  • date string: any date in the format supported by the parse () method var birthDate = new Date ("April 16, 1975"); document.write (birthDate);
  • year, month, day var birthDate = new Date (1975, 4, 28); document.write (birthDate);

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

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

When working with a Date object, it is important to remember that calculations are performed using Coordinated Universal Time (UTC), even though your computer may display the time according to your time zone.

Methods

MethodDescription
getDate ()Returns the day of the month (1 through 31) for the specified date, local time.
getDay ()Returns the day of the week (0 to 6; 0 = Sunday, 1 = Monday, etc.) for the specified date, local time.
getFullYear ()Returns the year (four digits).
getHours ()Returns the hour (0 to 23).
getMilliseconds ()Returns milliseconds (0 to 999).
getMinutes ()Returns the minutes (from 0 to 59).
getMonth ()Returns the month (0 to 11; 0 = January, 1 = February, etc.).
getSeconds ()Returns the seconds (from 0 to 59).
getTime ()Returns the number of milliseconds since midnight 01/01/1970.
getTimezoneOffset ()Returns the time difference between UTC and local time, in minutes.
getUTCDate ()Returns the day of the month UTC (1 through 31).
getUTCDay ()Returns the day of the week according to universal time (0 through 6).
getUTCFullYear ()Returns the UTC year (four digits).
getUTCHours ()Returns the UTC hour (0 to 23).
getUTCMilliseconds ()Returns milliseconds UTC (0 to 999).
getUTCMinutes ()Returns minutes in UTC (0 to 59).
getUTCMonth ()Returns the month in UTC (0 through 11).
getUTCSeconds ()Returns the seconds in UTC (0 to 59).
parse ()Parses a date string (for example, "May 21, 1992") and returns a date string that contains the number in milliseconds since January 1, 1970 00:00:00.
setDate ()Sets the day of the month for the specified date, local time (1 through 31).
setFullYear ()Sets the year (four digits).
setHours ()Sets the hour for the specified date according to local time (0 to 23).
setMilliseconds ()Sets the milliseconds for the specified date, local time.
setMinutes ()Sets the minutes (0 to 59).
setMonth ()Sets the month (0 to 11).
setSeconds ()Sets the seconds (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 according to universal time (four digits).
setUTCHours ()Sets the hour for the specified date, UTC.
setUTCMilliseconds ()Sets the milliseconds for the specified date, UTC.
setUTCMinutes ()Sets the minutes for the specified date, UTC.
setUTCMonth ()Sets the month for the specified date, UTC.
setUTCSeconds ()Sets the seconds for the specified date, UTC.
toDateString ()
toISOString ()Converts a date to a string using the ISO 8601 standard.
toJSON ()Returns the date as a string, formatted as a JSON date.
toLocaleDateString ()
toLocaleTimeString ()Returns the part of the date as a string, with a representation of the date based on system parameters.
toLocaleString ()Returns the date as a string, with a representation of the date based on system parameters.
toString ()Returns a string representing the specified Date object.
toTimeString ()Returns part of the date as a string.
toUTCString ()Converts a date to a string using the UTC timezone.
UTC ()Takes the same parameters as the long form of the constructor (i.e. 2-7) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.
valueOf ()Returns the primitive value of a Date object.

Date and time are part of our Everyday life and therefore figure prominently in programming. In JavaScript, when building a website, you might want to add a calendar, train schedule, or an interface for scheduling appointments. These applications must display the appropriate time points based on the user's current time zone, or perform calculations related to the arrival and departure of an aircraft or the start and end times of an event. Also, you may need to use JavaScript to send daily reports to certain time or for filtering (for example, to search for restaurants open at a certain time).

Date object

Date is inline JavaScript object which stores the date and time. It provides a number of built-in methods for formatting and manipulating this data.

By default, a new Date instance with no arguments creates an object with the current date and time according to system settings current computer.

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

// Set variable to current date and time
const now = new Date ();
// View the output
now;
Wed Oct 18 2017 12:41:34 GMT + 0000 (UTC)

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

The date and time are broken up and displayed in a readable way.

However, JavaScript interprets a date in terms of a Unix timestamp, which is a value consisting of the number of milliseconds since midnight January 1, 1970. You can get the timestamp using the getTime () method.

// Get the current timestamp
now.getTime ();
1508330494000

The large number that appears in the output as the current timestamp represents the number of milliseconds elapsed from midnight January 1, 1970 to October 18, 2017.

Zero time (or epoch time) is represented by the date string 01 January, 1970 00:00:00 Universal Time (UTC) and timestamp 0. You can test this in the browser by creating a new variable in the epoch.js file and assigning a new instance of Date to it based on time stamp 0.

// Assign the timestamp 0 to a new variable
const epochTime = new Date (0);
epochTime;
01 January, 1970 00:00:00 Universal Time (UTC)

Zero time was chosen as the standard for measuring time by computers, and this method is used in JavaScript. It is important to understand timestamps and date strings as these concepts can be used depending on the settings and purpose of the application.

Now you know how to create a new Date instance based on the current time and based on a timestamp. There are a total of four Date formats in JavaScript. In addition to the default current time and timestamp, you can also use a date string or specify a specific date and time.

To demonstrate different ways referring to a specific date, try creating new Date objects that represent July 4, 1776, 12:30 GMT 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);

All of these examples present the same date and time information in three different ways.

As you can see, the timestamp method has a negative number; any date before time zero will be represented as a negative number.

In the third example, seconds and milliseconds are represented by 0. If you are missing any data when you create the Date object, you should set them to 0. Missing data cannot be skipped because the order of the time data in the string does not change. It should also be noted that the month of July is designated here as 6, not as 7. This is because the countdown does not start from 1, but from 0. More on this in the next section.

Retrieving a date using get

Once you have a date, you can access all of its components using various built-in methods. The methods return each part of the date relative to the local time zone. Each of these methods starts with get and returns a relative number. Below is a detailed table of get methods for Date object.

Date Time Method Range Example
Year getFullYear () YYYY 1970
Month getMonth () 0-11 0 = January
Day of the month getDate () 1-31 1 = 1st of the month
Day of week getDay () 0-6 0 = Sunday
Hour getHours () 0-23 0 = midnight
Minute getMinutes () 0-59
Second getSeconds () 0-59
Millisecond getMilliseconds () 0-999
Time stamp getTime ()

// Initialize a new birthday instance
const birthday = new Date (1980, 6, 31);

All methods can now be used to retrieve each component of the date.

birthday.getFullYear (); // 1980
birthday.getMonth (); // 6
birthday.getDate (); // 31
birthday.getDay (); // 4
birthday.getHours (); // 0
birthday.getMinutes (); // 0
birthday.getSeconds (); // 0
birthday.getMilliseconds (); // 0
birthday.getTime (); // 333849600000 (for GMT)

Sometimes you only need to extract part of a date, and the built-in get methods will help you with that.

For example, you can compare the current date with the date of October 3 to find out if it is October 3 or not.

// Get today "s date
const today = new Date ();
// Compare today with October 3rd
if (today.getDate () === 3 && today.getMonth () === 9) (
console.log ("It" s October 3rd. ");
) else (
console.log ("It" s not October 3rd. ");
}
It "s not October 3rd.

The built-in get methods allow you to access date components.

Changing the date with set

All of the above getters have a corresponding setter. If get is used to retrieve a specific component of a date, set is used to change those components. Below is a detailed table of the set methods for the Date object.

Date Time Method Range Example
Year setFullYear () YYYY 1970
Month setMonth () 0-11 0 = January
Day of the month setDate () 1-31 1 = 1st of the month
Day of week setDay () 0-6 0 = Sunday
Hour setHours () 0-23 0 = midnight
Minute setMinutes () 0-59
Second setSeconds () 0-59
Millisecond setMilliseconds () 0-999
Time stamp setTime () Number of milliseconds since zero time

These setters can be used to change one or more date components. For example, you can change the year in the birthday variable to 1997.

// Change year of birthday date
birthday.setFullYear (1997);
birthday;
Thu Jul 31 1997 00:00:00 GMT + 0000 (UTC)

Now, when you call the birthday variable, you see not 1980, but 1997.

The built-in setter methods let you modify different parts of the Date object.

UTC methods

The get methods above retrieve date components based on local settings the user's time zone. To increase control over dates and times, you can use the getUTC methods, which work the same as get methods, but calculate the time based on UTC (Universal Time Coordinated). Below is a table of UTC methods for Date object in JavaScript.

Date Time Method Range Example
Year getUTCFullYear () YYYY 1970
Month getUTCMonth () 0-11 0 = January
Day of the month getUTCDate () 1-31 1 = 1st of the month
Day of week getUTCDay () 0-6 0 = Sunday
Hour getUTCHours () 0-23 0 = midnight
Minute getUTCMinutes () 0-59
Second getUTCSeconds () 0-59
Millisecond getUTCMilliseconds () 0-999

To check the difference between local getters and UTC getters, run the following code.

// Assign current time to a variable
const now = new Date ();
// Print local and UTC timezones
console.log (now.getHours ());
console.log (now.getUTCHours ());

This code will print the current time and time in UTC time zone. If you are currently in the UTC time zone, then the numbers that the program will output will be the same.

UTC provides an international time standard and therefore can keep code consistent with time zones if needed in your program.

Conclusion

In this tutorial, you learned how to instantiate a Date object, how to use its built-in methods to access and modify the components of a specific date. You can find more information about time and date in JavaScript on the Mozilla Developer Network.

Knowing how to work with dates is important for many common tasks in JavaScript, from creating regular reports to displaying dates and schedules in the correct time zone.

Tags:

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 = (new Date ()). getFullYear (); console.log (year); // Sample output: 2016

Get the current month

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

Note that 0 = 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 = (new Date ()). getDate (); console.log (day); // Sample output: 31

Get the current hour

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

Get current minutes

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

Get the current seconds

var seconds = (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 = (new Date ()). GetMilliseconds (); console.log (milliseconds); // Output: milliseconds right now

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

var now = 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 ());

Hello everyone!
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 a page in different formats (for example, in a 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 = new Date (), fd = 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 problems 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 = tempus (). format ("% d.% m.% Y");
Now about the speed. In the spoiler, you can see a comparison of Tempus with Moment and 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 are different, 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), not zero;
  • Milliseconds can be disabled (default) or enabled;
  • Fast work (Since, in many cases, a 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 ​​are 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, one more 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 will 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 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"); // Use format by default // "November 05" tempus (1383609600) .format ("% B,% d");
On this moment There are only two languages ​​- 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 see 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 = -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 ​​will be
filled with the minimum. List of constants with minimum values, you can see in 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 ​​from 1 to 12 (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 = 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 may notice that some parameters are set separately, while you could use regular expression... In fact, initially it was there, but after abandoning it, the speed increased several dozen times.
If you need to remove a 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 ​​using functions year (), month (), day (), hours (), minutes (), seconds (), milliseconds (), dayOfWeek (), utc (), timestamp () or set (). For example:
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 so we get the current year in numerical form

Generating dates

You can generate a date in a variety of ways, full list 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 are making our own calendar). Also, dates can be grouped by day, week, month, hour, year - whatever. This can also be applied to the calendar.

Plugins

Last but not least, plugins. Here we are expanding the factory to generate a random date. We also need the TempusDate class, which can be found in tempus.classes (). Here's an example plugin:
(function (tempus) (var TempusDate = tempus.classes ("TempusDate"); tempus.randomDate = function () (var date = new TempusDate (); date.year (Math.floor ((Math.random () * ( tempus.MAX_YEAR - tempus.MIN_YEAR)) + tempus.MIN_YEAR)). month (Math.floor ((Math.random () * (tempus.MAX_MONTH - tempus.MIN_MONTH)) + tempus.MIN_MONTH)). day (Math.random () * (tempus.MAX_MONTH - tempus.MIN_MONTH)) + tempus.MIN_MONTH)). day 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); // We can now create dates as follows var someRandomDate = 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 the attention!
P.S. Thanks for the invite!

Another useful thing for websites is the insertion of the current date. There are dozens of examples of date scripts on the Internet, but many of them, in my opinion, are heavy and, therefore, ugly. Meanwhile, using standard means JavaScript, it is very easy to insert a date on a website page. I use it very often! In the picture (screenshot from the current site) estate "Fairy Tale" !

Here is the entire date script:

In my opinion, it could not be easier, it is quite beautiful and understandable. If you have no desire to study the construction of this script, then simply paste it anywhere in the HTML page and you will get the following inscription:

Another more advanced option


! Today

It looks like this:

Today

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

More details:

So, we start by assigning a date value to a variable d, then create arrays ( Array) for the days of the week ( day) and months ( month), indicating them in the necessary grammatical form: case, number, capital letter if the word is at the beginning of a date, etc. The last line of the script is the actual date printing ( document.write). Here you set what and in what sequence you will display the current date in the string. The components are separated from each other by the sign + ... To enter a space, use the construction " " , and to enter the letter g (year) - the construction " G."

As you can see from the script, getting data about the current time is performed by the element get... This method provides the following information:

  • getDate ()- returns a number from 1 to 31 representing the day of the month;
  • getDay ()- returns the day of the week as an integer from 0 (Sunday) to 6 (Saturday);
  • getMonth ()- returns the number of the month of the year;
  • getFullYear ()- returns the year. To use simply getYear (), then the current year minus 1900 will be displayed;
  • get Hours ()- returns the hour of the day;
  • getMinutes ()- returns minutes as a number from 0 to 59;
  • getSeconds ()- returns the number of seconds from 0 to 59.

Paste directly Java-script inside the site page is not always convenient. Better to put the script description at the top of the page between tags and set a variable that we will call as needed in the text. Let's call it TODAY and define the date display form in it similarly to the above. The script will look like this:

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

If your site contains many pages on which you want to display the date, then it is more convenient to highlight Java-script for displaying the date in separate file, for example, data.js... In practice, this is a page consisting of the first of the described scripts, that is, with the line document.write(see above). It should be placed in the same directory as the main page, and called at the date output place as follows:

Don't forget to check that the file data.js had the same encoding as the main document, otherwise the date will be displayed with wonderful hooks, squares and other tweaks.

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 the exact time, then you need to use a PHP script that will show the time on the server.