JavaScript(JS) JS display date and time
In JavaScript, you can display the current date and time using the Date
object. Here's an example:
const currentDateTime = new Date(); console.log(currentDateTime);
In the above example, we create a new Date
object without any arguments, which sets the date and time to the current date and time. We then log the Date
object to the console, which displays the date and time in a string format.
If you want to display the date and time in a specific format, you can use the various methods of the Date
object to get the individual components of the date and time and concatenate them into a formatted string. Here's an example of displaying the current date and time in the format YYYY-MM-DD HH:MM:SS
:
const currentDateTime = new Date(); const year = currentDateTime.getFullYear(); const month = String(currentDateTime.getMonth() + 1).padStart(2, '0'); const day = String(currentDateTime.getDate()).padStart(2, '0'); const hours = String(currentDateTime.getHours()).padStart(2, '0'); const minutes = String(currentDateTime.getMinutes()).padStart(2, '0'); const seconds = String(currentDateTime.getSeconds()).padStart(2, '0'); const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; console.log(formattedDateTime);
In this example, we create a new Date
object and use the getFullYear()
, getMonth()
, getDate()
, getHours()
, getMinutes()
, and getSeconds()
methods to get the year, month, day, hours, minutes, and seconds components of the date and time. We then use the padStart()
method to add leading zeros to the strings if they are less than two characters long. Finally, we concatenate the year, month, day, hours, minutes, and seconds strings into a formatted string with the format YYYY-MM-DD HH:MM:SS
and log it to the console.