How to Display the Date with Javascript
In this article, we show how to display the date with Javascript.
In Javascript, we can display the date in several different formats. However, to do so, we must first create a Date object.
This is achieved by the following line:
var today= new Date();
using the above line, we create a Date object named today. Using this Date object, we can now display
the date in a variety of formats.
Display the Day and the Date
To display everything, the day it is and the current date, we use the method toDateString(), using the following format:
today.toDateString();
So to display it, the whole line would be:
Actual Javascript Output
Display Only the Year
To display only the year, again we create a Date object and then use the method So to display the current year, the lines of code to do so would be:
To display only the month, again we create a Date object and then use the method getMonth() to
obtain the current month.
However, this method does not return the month in words, say, June. Instead, it returns the number of the
month. But this is a little different. It doesn't start with 1 for January, as you probably are accustomed to seeing b
but starts with the index 0 for January. Therefore, the months are labeled from 0 to 11. 0 for January and 11 for
December. So it takes time to get used to this convention. If you can't get used to it, just skip this method.
To display the current month, the lines of code to do so would be:
Actual Javascript Code
Display Only the Month
Actual Javascript Code