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

note that Date() called without arguments is equivalent to new Date(Date.now()) .

Once you have a date object, you can apply any of several available methods to retrieve its properties (e.g. getFullYear() to get a 4 digit year).

Following are some common date methods.

Get current year

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

Get current month

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

Note that 0 = January. This is because the months vary from 0 before 11 , so it's often desirable to add +1 to the index.

Get current day

varday = (new Date()).getDate(); console log(day); // sample output: 31

Get 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 current seconds

var seconds = (new Date()).getSeconds(); console log(second); // sample output: 48

Get current milliseconds

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

var milliseconds = (new Date()).getMilliseconds(); console log(milliseconds); // Output: milliseconds right now

Convert current time and date to human readable string

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

Static Method Date.now() returns the number of milliseconds since January 1, 1970 00:00:00 UTC. To get the number of milliseconds that have passed since then using an instance of the Date object, 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());

Date and time are part of our Everyday life and therefore occupy a prominent place in programming. In JavaScript, when creating a website, you might need to add a calendar, train schedule, or an interface for scheduling appointments. These applications should show the appropriate times 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. In addition, you may need to use JavaScript to send daily reports at specific times or for filtering (for example, to find restaurants that are open at specific times).

date object

Date is a built-in JavaScript object that 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.

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

// 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 date string containing the following data:

The date and time are broken up and displayed in a way that is easy to read.

However, JavaScript interprets a date based on a Unix timestamp, which is a value consisting of the number of milliseconds that have elapsed 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 is the number of milliseconds that have passed since 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 the timestamp 0. You can check this in the browser by creating a new variable in the epoch.js file and assigning it a new instance of Date , based on timestamp 0.

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

Zero time has been 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 timestamp. There are four date formats in JavaScript in total. 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 various ways references 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 represent the same date and time information in three different ways.

As you can see, the timestamp method has a negative number; any date before zero time 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 must assign it to 0. Missing data cannot be omitted because the order of the time data in the string does not change. It should also be noted that the month of July here is designated as 6, not 7. This is because the countdown starts from 0, not 1. More on this in the next section.

Retrieving a date with 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 the 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 the week getDay() 0-6 0 = Sunday
Hour getHours() 0-23 0 = midnight
Minute getMinutes() 0-59
Second getSeconds() 0-59
Millisecond getMilliseconds() 0-999
timestamp getTime()

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

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

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 may be necessary to extract only part of a date, and the built-in get methods will help you with this.

For example, you can compare today's date with October 3rd to see if it's October 3rd 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

For all the get methods listed above, there is a corresponding set method. If get is used to retrieve a specific date component, set is used to change those components. Below is a detailed table of setter 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 the week setDay() 0-6 0 = Sunday
Hour setHours() 0-23 0 = midnight
Minute setMinutes() 0-59
Second setSeconds() 0-59
Millisecond setMilliseconds() 0-999
timestamp setTime() Number of milliseconds since 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 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 set methods allow you to change different parts of the Date object.

UTC Methods

The get methods described above retrieve the date components based on local settings user's time zone. To increase control over dates and times, you can use the getUTC methods, which work the same as the get methods, but calculate the time based on the UTC (Coordinated Universal Time) standard. Following is the 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 the week getUTCDay() 0-6 0 = Sunday
Hour getUTCHours() 0-23 0 = midnight
Minute getUTCMinutes() 0-59
Second getUTCSecons() 0-59
Millisecond getUTCMilliseconds() 0-999

To check the difference between local get methods and get UTC methods, 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 timezone. If you are currently in the UTC time zone, then the numbers that the program will display will be the same.

UTC provides an international time standard and can therefore support code according to 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 given date. More detailed information about time and date in JavaScript you can find on the Mozilla Developer Network.

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

Tags:

Getting the current date in JavaScript is very easy. This is what the Date object is for. Its syntax is quite simple and the method names are intuitive. In the examples below, I'll show you how to work with the Date object ( JavaScript new date) to get the current year, month, day and time to the nearest millisecond!

Getting the current date:

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

var date = new Date(); console log(date);

This code prints 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, current month, day of the month, year, and even the current time in 24-hour format. Fragment " GMT" means GMT time, and " -0500 ' is the difference in time zones between local time and GMT .

Quote from Wikipedia: "Greenwich Mean Time (GMT) GMT) is Mean Solar Time at the Royal Observatory, Greenwich, London." It's connected with UTC (UTC). « Eastern Standard Time The ' in the displayed date value refers to the time zone of your browser or computer.

* Please note that GMT and UTC are different. We will consider UTC values ​​in minutes.

* Also note that a date in JavaScript is defined by the time in milliseconds that has elapsed since midnight, January 01, 1970, UTC. There are 86,400,000 milliseconds in one day. The range of a Date object is -100,000,000 days to 100,000,000 days, relative to January 01, 1970 UTC.

* The values ​​obtained using the method mentioned above depend on the system settings of your device. If you change the computer's clock settings, the time returned by this method will also change.

Okay, we've got the new JavaScript Date formats out of the way and are now ready to move on!

Getting the day of the week:

To get the day of the week use the method JavaScript object Date getDay() :

varday = date.getDay(); console log(day);

*Note that the days of the week are numbered from 0 to 6, Sunday = 0, Monday = 1, Tuesday = 2, and so on.

Get the month:

To get the current month of the current year, use the getMonth() method. Before that, I said that the names of the methods are intuitive!

var month = date.getMonth(); console log(month); //one

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

Getting the day of the month:

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

var dayOfMonth = date.getDate(); console log(dayOfMonth); //2

* The 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.

vartime = date.getTime(); console log(time); //1454461242058

It 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 that?

1454461242058 ms / 31540000000 ms per year = about 46 years
1970 + 46 years = 2016

Let's check to make sure:

var year = date.getFullYear(); console.log(year) //2016

Yes, this is it! We just output the current date and time using JavaScript new date.


To work with dates and times in JavaScript, there is a special object - Date. This object is supported by almost all versions of JavaScript, and it can be used regardless of compatibility issues.

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

Creating a Date object is very simple:

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

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

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

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

Consider an example of working with dates:

And here is the output of this script:


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

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

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

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

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

Hi all!
I often have to work with statistical data and there is a lot tied to dates. Moreover, the same date can be used on the page in different formats (for example, machine-friendly and human-friendly). I think most of you have a pretty good idea of ​​all the horrendous code that comes out of using the 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 a lot of such lines? Is it easy to remember that in javascript, the month starts from zero when you develop not only on it? Or the fact that there are milliseconds here, and not seconds, as 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 you are interested, I suggest you read this short 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, the previous example could be written like this:
var fd = tempus().format("%d.%m.%Y");
Now about speed. In the spoiler, you can see a comparison of Tempus with Moment and the native date formatting (see above):

Comparison of native JS, MomentJS and TempusJS

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 auto-detection and parsing
Native JS x 11,204,316 ops/sec ±0.81% (88 runs sampled) Moment x 38,511 ops/sec ±1.41% (95 runs sampled) Tempus x 93,973 ops/sec ±1.06% (85 runs sampled)
Parsing date by format
Moment x 46.293 ops/sec ±0.63% (100 runs sampled) Tempus x 109.947 ops/sec ±0.93% (99 runs sampled)
Parsing and validation
Moment x 44,588 ops/sec ±1.09% (90 runs sampled) Tempus x 103,439 ops/sec ±0.90% (94 runs sampled)
The results are from my laptop in Google Chrome 30.0.1599.114. In other browsers, the results are different, but the ratio remains about the same.
For tests, the benchmark.js library was used
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 at 1 (default) instead of zero;
  • Milliseconds can be disabled (default) or enabled;
  • Fast work (Because, in many cases, the browser's 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 (because the validation takes place already when entering values, and is not calculated separately);
  • Multilingualism and auto-detection of the user's language.

Here we will talk about only some of the functions.

Formatting and parsing

So, for starters, another example of date formatting. Here we also use call chaining. At the end of each value setting, we get back a TempusDate object that we can use further down the chain. Example:
tempus(). // get 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 date parsing.
// 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 specific format, then parsing will be faster. Plus, you can set the date that will be returned if the parsing fails:
// Because "123" does not match the format "%d.%m.%Y", then // an object containing the date 2013-01-01 will be returned tempus("123", "%d.%m.%Y", tempus ());
You can see the list of default formats

Now let's change the format of the already formatted date
// "2013-11-05" tempus("11/05/2013").format("%Y-%m-%d"); // Or like this // "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 language tempus.lang("ru"); // Standard use format // "Nov, 05" tempus(1383609600).format("%B, %d");
On the this moment There are only two languages ​​- Russian and English, so I will be glad to help.

Validation

Date validation happens like this:
// 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 year=-5, i.e. invalid errors(); // get an 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 desired format("year", "month", "day", "hours", "minutes", "seconds", "milliseconds").
Here is a simple example to get 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 minimal. List of constants with minimum values, you can see in the documentation.

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

Own formats

We apply our own format for the month, which can take values ​​from 1 to 12 (instead of 01 to 12):
// Register a new format tempus.registerFormat("%q", // directive - %q function(date) ( // Specify the formatting function here, 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 value 2 can take , // Max length "number" // Type); // Testing // Will return "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, it was there initially, but after abandoning it, the speed increased several dozen times.
If you need to remove some format, then use unregisterFormat:
tempus.unregisterFormat("%d"); // Returns "%d.01.2013" because the %d directive no longer exists. tempus.format((year: 2013, month: 1, day: 1), "%d.%m.%Y");

Getters/Setters

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

Date Generation

You can generate a date in many ways, full list parameters is in the documentation. Here is a minimal example.
// returns ["29.03.2013", "30.03.2013", "31.03.2013", "01.04.2013", "02.04.2013"]; tempus.generate(( dateFrom: "20130329", formatFrom: "%Y.%m.%d", dateTo: "20130402", period: (day: 1), format: "%d.%m.%Y" ));
This can be useful for displaying charts by dates and changing the display format directly on the client, without requests to the backend. The date can be generated as an array or as objects, where the dates themselves will be used as keys (this is useful when we need to bind an event to a date, for example, when we make our own calendar). Also, dates can be grouped by days, weeks, months, hours, years - whatever. This can also be applied to the calendar.

Plugins

Last but not least, plugins. Here we are extending the factory to generate a random date. Also, we need the TempusDate class, which can be found in tempus.classes(). Here is 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. floor((Math.random()*(date.dayCount() - tempus.MIN_DAY)) + tempus.MIN_DAY)).hours(Math.floor((Math.random()*(tempus.MAX_HOURS - tempus.MIN_HOURS) ) + tempus.MIN_HOURS)).minutes(Math.floor((Math.random()*(tempus.MAX_MINUTES - tempus.MIN_MINUTES)) + tempus.MIN_MINUTES)).seconds(Math.floor((Math.random() *(tempus.MAX_SECONDS - tempus.MIN_SECONDS)) + tempus.MIN_SECONDS)); return date; ); ))(tempus); // Now we can create dates like this var someRandomDate = tempus.randomDate();
I think that in this way it will be possible to conveniently write widgets using jQuery + Tempus, Angular + Tempus, etc.

Sources

You can install it by downloading the source code from 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 given 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 your attention!
P.S. Thanks for the invite!