How To Get Current Date In Javascript

When working with JavaScript and web development, sometimes you may need to display the current date or manipulate the date in various ways. With JavaScript being a versatile and widely-used programming language, it offers various ways to get the current date.

Getting the Current Date and Time

To get the current date and time in JavaScript, you can simply create a new Date object using the new Date() constructor. The Date object will automatically initialize with the current date and time. Here’s an example:

const currentDate = new Date();
console.log(currentDate); // Output: current date and time

This code will output the current date and time, including the year, month, day, hours, minutes, seconds, and milliseconds.

Formatting the Date

Now that we have the current date and time, you may want to format it in a specific way. JavaScript offers various methods to get different parts of the date, such as:

  • getFullYear(): Get the full year (4 digits)
  • getMonth(): Get the month (0-11, where 0 is January)
  • getDate(): Get the day of the month (1-31)
  • getHours(): Get the hours (0-23)
  • getMinutes(): Get the minutes (0-59)
  • getSeconds(): Get the seconds (0-59)
  • getMilliseconds(): Get the milliseconds (0-999)

Let’s say you want to display the date in the format “YYYY-MM-DD”. You can achieve this using the following code:

const currentYear = currentDate.getFullYear();
const currentMonth = currentDate.getMonth() + 1; // Add 1 to get the correct month number
const currentDay = currentDate.getDate();

const formattedDate = `${currentYear}-${currentMonth.toString().padStart(2, '0')}-${currentDay.toString().padStart(2, '0')}`;
console.log(formattedDate); // Output: YYYY-MM-DD

Note that we used toString().padStart(2, ‘0’) for the month and day to ensure they are always 2 digits long.

Displaying the Date on a Web Page

To display the formatted date on a web page, you can use the innerHTML property to set the content of an HTML element. Here’s an example:

const dateElement = document.getElementById('current-date');
dateElement.innerHTML = formattedDate;

And in your HTML, add the following element:

<span id="current-date"></span>

Now the current date in the “YYYY-MM-DD” format will be displayed on your web page.

Conclusion

JavaScript provides various ways to get and format the current date using the Date object and its methods. With this knowledge, you can now display or manipulate the current date as needed in your web projects.