YogeshChauhan . com

4 ways to create Date Objects in JavaScript

in JavaScript on 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

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to uninstall Cocoapods from the Mac OS? #4 How to add Read More Read Less Button using JavaScript? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

May 5 Use inline if to make a shorter conditional syntax in React May 4 What is Conditional Rendering in React? May 3 How does @extend rule work in SCSS (Sass)? May 2 How different is Handling Events in React vs HTML DOM? May 2 How to create bouncing balls using HTML canvas and JavaScript? Apr 30 HTML canvas methods

You might also like these

2 Ways We Can Write Multiple Line Commands in PHPPHPWhat is Hoisting in JavaScript?JavaScriptShort-Circuit Evaluation in JavaScriptJavaScriptHow to apply style to the first-child using jQuery?jQueryHow to get category name using post id in WordPress?WordPressHow to Secure Web or Mobile Browsers?Misc