How to display date and time in Javascript?

How to display date, time, and history in Javascript with code Examples 2023?

To work with time and date in JavaScript, you can use the Date object. The Date object has a number of methods that allow you to get and set the date and time, as well as format the date and time in different ways.


How to display date and time in Javascript


Here are some of the most common date in javascript methods:


new Date(): This method creates a new Date object with the current date and time.

getDate(): This method returns the day of the month.

getMonth(): This method returns the month of the year (0-11).

getFullYear(): This method returns the year.

getHours(): This method returns the hour of the day (0-23).

getMinutes(): This method returns the minutes of the hour (0-59).

getSeconds(): This method returns the seconds of the minute (0-59).

getMilliseconds(): This method returns the milliseconds of the second (0-999).

toDateString(): This method returns a string representation of the date in the format "YYYY-MM-DD".

toTimeString(): This method returns a string representation of the time in the format "HH:mm:ss".

toLocaleString(): This method returns a string representation of the date and time in the local time zone.

You can also use the Date object to create timestamps, which are numbers that represent the number of milliseconds since January 1, 1970. You can use timestamps to compare dates and times or to calculate the difference between two dates.


Here is an example of how to get the current date and time using the Date object:


const now = new Date();


console.log(now); // "2023-09-07T09:10:27.000Z"

This code creates a new Date object called now and then prints the value of now to the console. The value of now is a string that represents the current date and time in the format "YYYY-MM-DDTHH:mm:ss.sssZ".


You can also use the Date object to format the date and time in different ways. For example, the following code formats the current date and time in the format "Month Day, Year":


const now = new Date();


const formattedDate = now.toLocaleString();


console.log(formattedDate); // "September 7, 2023"

This code creates a new Date object called now and then formats the value of now using the toLocaleString() method. The toLocaleString() method returns a string representation of the date and time in the local time zone.


Example:


Output:


display date and time in Javascript

Comments :

Post a Comment