Wednesday, January 22, 2025
HomeProgrammingHow do you get the current date and time in JavaScript?

How do you get the current date and time in JavaScript?

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:

See also  How can I find where Python is installed on Windows?

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:

See also  How do I comment out a block of tags in XML?

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).

See also  What is JavaScript Anonymous Function?

 

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x