1. Using new Date()

new Date() creates a new date object with the current date and time.


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

// 2020-08-17T01:32:40.419Z

2. Using new Date() with parameters

If we pass parameters, new Date() creates a new date object with a specified date and time.

We can specify year, month, day, hour, minute, second and millisecond in that order.


var date = new Date(2020, 6, 4, 1, 3, 20, 0);
console.log(date);

// 2020-07-04T01:03:20.000Z

enlightened Remember: JavaScript counts months from 0 to 11.

If we specify 6 numbers, then it will take those for year, month, day, hour, minute and second. Millisecond will be set as 0.


var date = new Date(2020, 6, 4, 1, 3, 20);
console.log(date);

// 2020-07-04T01:03:20.000Z

If we specify 5 numbers, then it will take those for year, month, day, hour and minute. Second and Millisecond will be set as 0.


var date = new Date(2020, 6, 4, 1, 3);
console.log(date);

// 2020-07-04T01:03:00.000Z

If we specify 4 numbers, then it will take those for year, month, day and hour. Minute, Second and Millisecond will be set as 0.


var date = new Date(2020, 6, 4, 1);
console.log(date);

// 2020-07-04T01:00:00.000Z

3. new Date() from string

We can create from a date string. We just need to pass the string as parameter.


var date = new Date("July 8, 1997 10:23:10");
console.log(date);

// 1997-07-08T10:23:10.000Z

4. new Date() from milliseconds

We can create from a number (milliseconds). We just need to pass the number as parameter.


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

// 2001-09-09T01:46:40.000Z

You can also specify negative milliseconds.


var date = new Date(-1000000000000);
console.log(date);

// 1938-04-24T22:13:20.000Z

0 Comments

Leave a reply

Your email address will not be published. required fields are marked *