You can use the Date object in JavaScript to display the current date and time. The Date object has various methods that can be used to get different parts of the date and time, such as the year, month, day, hours, minutes, and seconds.

Here is an example that shows how to display the current date and time in JavaScript:

var date = new Date();
document.getElementById("date-time").innerHTML = date.toLocaleString();

In the above example, a new Date object is created and assigned to the variable date. Then the toLocaleString() method is used to get a string representation of the date and time, formatted according to the user’s local settings. The resulting string is then displayed in an element with the id “date-time”.

You can also use the toLocaleDateString() and toLocaleTimeString() methods separately to get the date and time parts respectively.

var date = new Date();
var dateString = date.toLocaleDateString();
var timeString = date.toLocaleTimeString();
document.getElementById("date").innerHTML = dateString;
document.getElementById("time").innerHTML = timeString;

You can also use the getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), and getSeconds() methods to get the specific parts of the date and time, and then format them as needed.

var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1; //getMonth() method returns a 0-based value, so we need to add 1
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
document.getElementById("date-time").innerHTML = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

It’s worth noting that the Date object returns the date and time based on the user’s device time, so it’s important to be aware of potential time zone differences when working with date and time in JavaScript.

Also Read:

Categorized in: