How do I get the current date in JavaScript?

How do I get the current date in JavaScript?
How do I get the current date in JavaScript?

There are a few ways to get the current date in JavaScript, depending on what you’re trying to do.

The simplest way is to use the Date object, which is built into JavaScript. Here’s an example of how you can use it to create a new Date object representing the current date and time:

var currentDate = new Date();
console.log(currentDate);

You can also pass in a date string to create a Date object representing a specific date. For example:

var birthday = new Date("January 1, 1990");
console.log(birthday);

If you want to format the date in a specific way, you can use the various methods provided by the Date object.

Here’s an example of how you can use the toDateString() method to format the date as a string:

var currentDate = new Date();
console.log(currentDate.toDateString());

which will output date in string form : Mon Jan 10 2022

You can also use other methods like toUTCString() or toISOString() to format the date and time in a specific way.

You can also use getDate(),getMonth() and getFullYear() method to get day, month and year respectively

var currentDate = new Date();
console.log(currentDate.getDate());
console.log(currentDate.getMonth());
console.log(currentDate.getFullYear());

Keep in mind that the Date object is based on the number of milliseconds that have passed since January 1, 1970, so the output of the Date object may be affected by time zone differences.

Leave a Reply