YogeshChauhan.com
4 ways to create Date Objects in JavaScript
August 18, 2020

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

📌 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
dreamhost

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress? Mar 3 substring() Method in JavaScript Mar 3 Window setInterval() Method in JavaScript Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS

You might also like these

The SQL UNION OperatorSQL/MySQLWhat are CSS Specificity Rules and how does browser apply them?CSSLearn how to add Scroll Indicator using CSS and JavaScript?CSSHow to overwrite file contents with new content in PHP?PHPThe difference between isFinite() method and isFinite() function in JavaScriptJavaScriptLearn to Implement Estimated Reading Time using PHP Part 1: The BasicsPHP