Convert Days to String using JavaScript
In this example, I am using JavaScript .getDay() method to get the day of the week. It will return a numeric value and I’ll convert it to a string value.
Syntax
objDate.getDay()
The Code
<html> <body> <p>Click the Button to convert an Array to a String</p> <p> <input type="button" value="Convert Array to String" onclick="convertArrayToString()" /> </p> <div id="t"></div> </body> <script> function convertArrayToString() { var dt = new Date(); // THE DATE OBJECT. // ADD WEEK DAYS IN AN ARRAY. var weekday = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); // GET THE DAY. document.getElementById('t').innerHTML = "Today is <b>" + weekday[dt.getDay()] + "</b>"; } </script> </html>
The value returned by .getDay() (a number) is used as an index in the array, which will return a day (string) in the array.
Convert Months to String using JavaScript
Similarly, in this example I am using JavaScript .getMonth() method to get the month of the year. Like, the .getDay() method, the .getMonth() too returns a numeric value 0 to 11. Therefore, to get the month in string, I’ll create an array of months and use the value of .getMonth() as an index to fetch the result from the array.
The Script
<html> <body> <p>Click the button to see the Current Month.</p> <p> <input type="button" value="Get the Current Month" onclick="getCurrentMonth()" /> </p> <div id="t"></div> </body> <script> function getCurrentMonth() { var dt = new Date(); // THE DATE OBJECT. // ADD MONTHS IN AN ARRAY. var months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); document.getElementById('t').innerHTML = "The Current Month is: <b>" + months[dt.getMonth()] + "</b>"; } </script> </html>
Browser Support:
Chrome 39.0 - Yes | FireFox 34.0 - Yes | Internet Explorer 10 - Yes | Safari - Yes