Yogesh Chauhan's Blog

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

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 add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Dec 4 What is Etrieve Flow? #Dec 2 The unique operator($) in Envision Basic #Nov 25 Steps to Install Microsoft SQL Server on a MacOS #Nov 11 What is DevOps? #Nov 10 The * arithmetic operator in Envision Basic #Nov 10 What are Big Data Clusters in SQL Server?
You might also like these
How to deploy Angular App on Dreamhost or Amazon S3 or firebase?AngularHow to create a simple digital clock using JavaScript?JavaScriptThe basics of @import rule in SCSS (Sass)SCSSHow to Clone Objects in PHP?MiscellaneousHow to get Current Hour, Minute and Second in JavaScript?JavaScriptHow to add a Bar Chart in Angular App?Angular