By using getMonth()
method we can return the name of the month in JavaScript.
<p>Click the below button to get present month.</p> <input type="button" value="Click" onclick="myDate()" /> <p id="myId"></p> <script> function myDate() { var a = new Date(); var month = new Array(); month[0] = "January"; month[1] = "February"; month[2] = "March"; month[3] = "April"; month[4] = "May"; month[5] = "June"; month[6] = "July"; month[7] = "August"; month[8] = "September"; month[9] = "October"; month[10] = "November"; month[11] = "December"; var r = month[a.getMonth()]; document.getElementById("myId").innerHTML = r; } </script>
In the above code snippet we have given Id
as "myId
"to the second <p>
element in the HTML code. There is a function myDate() in the<script>
block which is connected to the Onclick of the HTML button. We have given new Date()
to the variable A
, which returns the day, date, year, month & time. There are 12 months in a year, we are representing all the months as an new Array() with the variable "month". For all the months we will give numbering from 0 to 11 (January=0, February=1, March=3,............................,December=11). Onclick of the button fires the function myDate() in the <script>
block at the same time getMonth()
returns the name of the month as output.
OUTPUT
Views: 13892 | Post Order: 105