You can get the current date and time in JavaScript using the Date() object.
Here’s a simple example:
JavaScript
const now = new Date();
console.log(now);
This code will output the current date and time in a format like this:
2024-07-20T14:28:15.203Z
To get specific parts of the date and time:
Year: now.getFullYear()
Month: now.getMonth() (Note: Months are 0-indexed, so January is 0)
Day: now.getDate()
Hours: now.getHours()
Minutes: now.getMinutes()
Seconds: now.getSeconds()
Milliseconds: now.getMilliseconds()
To format the date and time:
You can use methods like toLocaleString() or toISOString() to format the date and time according to your needs. For example:
JavaScript
const formattedDate = now.toLocaleString();
console.log(formattedDate); // Output: “7/20/2024, 2:28:15 PM” (format may vary depending on your locale).