Friday 30 September 2011

Javascript code to get first day of a month

<html>
<head>
<script type="text/javascript">

function getFirstDay (date,month,year) {

var dateObj =  new Date();
dateObj.setFullYear(year);
alert(dateObj.getFullYear());

month_names = new Array("January","February","March","April","May","June","July",

"August","September","October","November","December");
dateObj.setMonth(month);
var m_name = dateObj.getMonth();
alert(month_names[m_name]);

day_names = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
dateObj.setDate(1);
var first_day = dateObj.getDay();

alert(day_names[first_day]);
}
</script>
</head>
<body>
<input type ='button' value='Get First Day' onclick = 'getFirstDay(1,0,2013)' />
</body>
</html>
 
 
From the html code i called a function getFirstDay( ) with parameters date, month, year
The first step is to create a dateobject and make calls to the library functions
The functions setFullYear, setMonth, setDate sets the date, month, year we are passing into it.
Two arrays, day_names and month_names are declared to hold the week day names and month names
It’s obvious that the every month starts with a date 1.
So, the setDate(1) sets the date ’1′.
getDay() returns the day