Loading, please wait...

MCQ

How to work with Dates in JavaScript

Aug 28, 2020 html, date, javascript, date function , 1586 Views
There are defined instructions to with Dates in JavaScript. It is very handy and useful for working on live projects. Date objects are created by defining new Date(); constructor. Which can be saved in a variable or constant to be used later.

How to work with Dates in JavaScript

There are defined instructions with Dates in JavaScript. It is very handy and useful for working on live projects. Date objects are created by defining new Date(); constructor. Which can be saved in a variable or constant to be used later.

Example:

const myDate = new Date();

console.log(myDate);

Result:

NOTE: By default, JavaScript will use the browser's time zone and display a date as a full-text string.

To avail of the details from the date, you can collect them in variables by specifying it.

Example:

var d = new Date(124125321471);

console.log(d.toString());

Answer:

Fri Dec 07 1973 20:45:21 GMT+0530 (India Standard Time)

Or

var d = new Date('2016-03-02T11:30:00');

console.log(d.toString());

Answer:

Wed Mar 02 2016 11:30:00 GMT+0530 (India Standard Time)

This method is generally used for constructing instances.

Or

var d = new Date(year, index of month, date, hours, minutes, seconds, milliseconds);

var d = new Date(2016, 03, 02, 11, 30, 27, 0);

//you can also add time zones

NOTE: Index of months starts from 0 and ends on 11 and the last parameter is stating month in the function.

There are different methods to get specific data out of a given date. For instance, if the user wants to acquire the year or month or just the date from the given data.

Example:

var d = new Date(2016, 03, 02, 11, 30, 27, 0);

console.log(d.getFullYear());

Answer:

There are many others :

  • .getMonth();
  • .getDay());
  • .getTime())

Many more…

If the new Date(); is kept empty that is without any arguments then all the above codes will show you the respective date, time, year, and more according to your local time zone.

The time value input can also be altered or changed with the help of JavaScript. This is done by taking the variable followed by .set then the parameter you want to change.

Example:

d.setDate(15);

console.log(d.toString())

Fri Apr 15 2016 11:30:27 GMT+0530 (India Standard Time)

Similarly every aspect of the value from new Date(); can be changed, there are

  • setFullYear(X);
  • setMonth(X);

many more…

MCQ

Related Article