How to make a date javaScript

Learn how to create & format dates using JavaScript with an easy to follow example.

Creating a Date Object in JavaScript

JavaScript offers a wide range of Date objects to store, manipulate and format dates and times. It is possible to create a Date object in two ways: using the new operator, or using the Date.parse() method. The new operator is used to create a new instance of the Date object, while the Date.parse() method is used to parse a string representing a date and time and create a Date object.

In this article, we will look at how to create a Date object using the new operator. To do this, we need to specify the year, month, day, hour, minute, second, and millisecond values for the Date object.

// Create a new Date object
var date = new Date(year, month, day, hours, minutes, seconds, milliseconds);

The year value is a four-digit number representing the year. The month value is a number from 0 to 11, representing the months of January to December. The day value is a number from 1 to 31, representing the day of the month. The hours, minutes, seconds, and milliseconds values are all numbers from 0 to 59.

For example, if we want to create a Date object for the 15th of January, 2020, at 11am and 15 seconds, we can do so as follows:

// Create a Date object for 15th January, 2020, 11am and 15 seconds
var date = new Date(2020, 0, 15, 11, 0, 15);

console.log(date); // Mon Jan 15 2020 11:00:15 GMT+0100 (Central European Standard Time)

As you can see, the Date object is created with the correct date and time. We can also use the Date object to access individual parts of the date and time, such as the year, month, day, etc. To do this, we can use the getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds(), and getMilliseconds() methods.

// Get year, month, day, etc. from the Date object
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
var millisecond = date.getMilliseconds();

console.log(year); // 2020
console.log(month); // 0
console.log(day); // 15
console.log(hour); // 11
console.log(minute); // 0
console.log(second); // 15
console.log(millisecond); // 0

We can also use the Date object to format the date and time as a string. To do this, we can use the toLocaleDateString() and toLocaleTimeString() methods.

// Format the date and time as strings
var dateString = date.toLocaleDateString();
var timeString = date.toLocaleTimeString();

console.log(dateString); // 15/1/2020
console.log(timeString); // 11:00:15

In this article, we looked at how to create a Date object in JavaScript using the new operator. We also looked at how to access individual parts of the date and time using the getXXX() methods, and how to format the date and time as strings using the toLocaleDateString() and toLocaleTimeString() methods.

Answers (0)