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

amazon

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

#Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS? #Aug 1 What is Zdog? #Aug 1 How to add before after image effect using pure CSS? #Jul 31 Add animation to your skills bar using CSS #Jul 31 Use SwiperJS to create mobile touch sliders fast
You might also like these
How to convert an object from API to JSON array in Angular 9?AngularHow to scroll contents of a an element vertically using JavaScript?JavaScriptWhat is an API?MiscellaneousThe difference between 400(4xx) and 500(5xx) errorsMiscellaneous@mixin and @include in SCSS (Sass)SCSS3 JavaScript methods to use when you want to go back and forth in historyJavaScript