JavaScript is a programming language used to make web pages
interactive without communication with server side. It runs on visitor's
computer and client browser interprets and executes it.
JavaScript is
having a vast library of functions. We can derive new functions based upon
these functions. I am creating a function to calculate total days of a month of
any year. Most months have same days in every year but February has either
28/29. That’s why year has importance in this calculation.
The below code
snippet shows a HTML page with a text box to input date in format MM/DD/YYYY by
user. Second text box shows total number of days on click of a button with
label Calculate Days.
There is a JavaScript
function GetMonthDays that reads date from input text box, calculates days from
month mentioned in input date and shows total days of that month in text box
txtDays.
The code or
trick to calculate the days in a month is written on line 8.
var calcDate
= new Date (inputDate.getFullYear(), inputDate.getMonth()+1, 0);
A date object
is created by taking year, month data from date input by user.
The FullYear()
method returns four digits year of the specified date.
The getMonth()
method returns the month (from 0 to 11) for the specified date.
inputDate.getMonth()+1
passes next month and
0 as a day
results in last day of previous month and hence I have a date object with last
day of specific month.
