Solved

how many days in a month using javascript

Posted on 2014-02-03
3
201 Views
Last Modified: 2014-02-03
Hi,

I need a code to know how many days are in a specific month of a specific year, any idea? I need it in javascript
0
Comment
Question by:joyacv2
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 19

Accepted Solution

by:
Ken Butters earned 500 total points
ID: 39830126
found the following code that exists on several different sites.


function numberOfDays(year, month) {
    var d = new Date(year, month, 0);
    return d.getDate();
}

Open in new window


The month input paramter on the constructor of date takes a value from 0 to 11, but this solution requires the month AFTER then one you really want...

The day is from 1 to 31

Using a day parameter of 1 forces the date constructor to back up to the last day of the prior month..

d.getDate gives you that last day.

Example request:


var numDays = numberOfDays(2012,6);

That will return number of days in June, 2012.
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 39830137
Since only February ever changes, you just need to test for leap year.
//year to test example
	var yr = 1990;
	// check for leap year, February number of days (28 or 29)
	var febDays = (((yr % 100 !== 0) && (yr % 4 === 0)) || (yr % 400 === 0)) ? 29 : 28;

Open in new window

0
 
LVL 1

Author Closing Comment

by:joyacv2
ID: 39830147
works perfect!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question