Home / JavaScript / JavaScript Date and Time – The Date() object
The getMonth() function gives us the month in a numeric form. To convert this value into the month name, we will employ an array. The array would contain all the 12 month names.
<script type="text/javascript"> <!-- var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); var d = new Date(); var curr_date = d.getDate(); var curr_month = d.getMonth(); var curr_year = d.getFullYear(); document.write(curr_date + "-" + m_names[curr_month] + "-" + curr_year); /* The last two lines above have to placed on a single line */ //--> </script>
Note: For the sake of clarity, I’ve written the JavaScript code for the array in multiple lines. For usage, you would have to put this on a single line.
This time, we use the new operator with the Array() constructor and store the 12 month names in the array. Variable m_names stores the array of month names.
The value returned by getMonth() is the index at which the month name is stored in the array. Indexes in JavaScript arrays begin at 0; this suits our purpose and we do not need to increment the getMonth() value.
The code above prints:
In this format we include a superscript to the date value. The idea is to identify the date and then select a superscript based on the date value.
<script type="text/javascript"> <!-- var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); var d = new Date(); var curr_date = d.getDate(); var sup = ""; if (curr_date == 1 || curr_date == 21 || curr_date ==31) { sup = "st"; } else if (curr_date == 2 || curr_date == 22) { sup = "nd"; } else if (curr_date == 3 || curr_date == 23) { sup = "rd"; } else { sup = "th"; } var curr_month = d.getMonth(); var curr_year = d.getFullYear(); document.write(curr_date + "<SUP>" + sup + "</SUP> " + m_names[curr_month] + " " + curr_year); //--> </script>
Note: The last line of code has been split up into two lines. For usage, the entire code should be written on a single line.
We first initialize a variable sup that would store the superscript value. Using If-Else-If, we check the value of the current date and accordingly assign a value to sup.
The code prints:
How do I view a deleted web page?
Is there a way to view a deleted web page - one that is no longer available? Yes there is and the solution is quite simple. [more...]
Because of its prevalent use, Oxford English Dictionaries named "Selfie" the Word Of The Year in 2013. [more...]
We use cookies to give you the best possible website experience. By using WebDevelopersNotes.com, you agree to our Privacy Policy