Date and Time - Javascript

date and time are very essential elements of any programming language

In Javascript we have date object

const today = new Date();
console.log(today);

Output: 

Tue Mar 05 2019 21:21:52 GMT+0530 (India Standard Time)

 

 

 

To check type of date type

const today = new Date();
console.log(typeof today);

Output:

object

 

 

 

To convert date object to String

const today = new Date();
console.log(today.toString());

console.log(typeof today.toString());

Output:

Tue Mar 05 2019 21:40:54 GMT+0530 (India Standard Time)
string

 

 

Specify a date

const today = new Date('01-12-1982');
console.log(today);

Output:

Tue Jan 12 1982 00:00:00 GMT+0530 (India Standard Time)

 

 

You can also specify time along with date

const today = new Date('01-12-1982 23:55:01');
console.log(today);

Output:

Tue Jan 12 1982 23:55:01 GMT+0530 (India Standard Time)

 

 

You can also declare date using different formats

const date1 = new Date('March 15 2011');
const date2 = new Date('9/7/1990');
console.log(date1);
console.log(date2);

Output:

Tue Mar 15 2011 00:00:00 GMT+0530 (India Standard Time)
Fri Sep 07 1990 00:00:00 GMT+0530 (India Standard Time)

 

const date = new Date('March 15 2011 23:52:03');

// Get Month
// Months are zero indexed, so march will be 2 not 3
console.log(date.getMonth());

// Get Date
console.log(date.getDate());

// Get Day
console.log(date.getDay());

// Get Full year
console.log(date.getFullYear());

// Get Hours
console.log(date.getMonth());

// Get Minutes
console.log(date.getMinutes());

// Get Seconds
console.log(date.getSeconds());

// Get Milli Seconds
console.log(date.getMilliseconds());

// Get Time (Seconds since epoch 1-1-1970)
console.log(date.getTime());

Output:

 

We can also change the date (Almost anything in date object like month year time etc.)

 

Change Date

const date = new Date('March 15 2011 23:52:03');

date.setDate(25);
console.log(date);

Output:

Fri Mar 25 2011 23:52:03 GMT+0530 (India Standard Time)

 

Change Month

const date = new Date('March 15 2011 23:52:03');

date.setMonth(7);
console.log(date);

Output:

Mon Aug 15 2011 23:52:03 GMT+0530 (India Standard Time)

 

 

Change Full year

const date = new Date('March 15 2011 23:52:03');

date.setFullYear(1980);
console.log(date);

Output:

Sat Mar 15 1980 23:52:03 GMT+0530 (India Standard Time)

 

Change Hour

const date = new Date('March 15 2011 23:52:03');

date.setHours(13);
console.log(date);

Output:

Tue Mar 15 2011 13:52:03 GMT+0530 (India Standard Time)

 

Change Minutes

const date = new Date('March 15 2011 23:52:03');

date.setMinutes(57);
console.log(date);

Output:

Tue Mar 15 2011 23:57:03 GMT+0530 (India Standard Time)

 

Change Seconds

const date = new Date('March 15 2011 23:52:03');

date.setSeconds(44);
console.log(date);

Output:

Tue Mar 15 2011 23:52:44 GMT+0530 (India Standard Time)

 

 

 

 

 

 

None