Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate number of days in a given month

Tags:

javascript

Performance is of the utmost importance on this one guys... This thing needs to be lightning fast!


How would you validate the number of days in a given month?

My first thought was to make an array containing the days of a given month, with the index representing the month:

var daysInMonth = [     31, // January     28, // February     31, // March     etc. ]; 

And then do something along the lines of:

function validateDaysInMonth(days, month) {     if (days < 1 || days > daysInMonth[month]) throw new Error("Frack!"); } 

But... What about leap years? How can I implement checking for leap years and keep the function running relatively fast?


Update: I'd like you guys to show me some code which does the days in month- leap year validation.

Here's the flowchart describing the logic used today:


(source: about.com)

like image 329
cllpse Avatar asked Sep 16 '09 13:09

cllpse


People also ask

How do you know if a month has 30 or 31 days JavaScript?

JavaScript getDate() Method: This method returns the number of days in a month (from 1 to 31) for the defined date. Return value: It returns a number, from 1 to 31, representing the day of the month.


2 Answers

function daysInMonth(m, y) { // m is 0 indexed: 0-11     switch (m) {         case 1 :             return (y % 4 == 0 && y % 100) || y % 400 == 0 ? 29 : 28;         case 8 : case 3 : case 5 : case 10 :             return 30;         default :             return 31     } }  function isValid(d, m, y) {     return m >= 0 && m < 12 && d > 0 && d <= daysInMonth(m, y); } 
like image 56
nickf Avatar answered Oct 09 '22 13:10

nickf


I've been doing this using the Date object (assuming it's compiled, and hence blindingly fast compared to scripting).

The trick is that if you enter a too high number for the date part, the Date object wraps over into the next month. So:

var year = 2009; var month = 1; var date = 29;  var presumedDate = new Date(year, month, date);  if (presumedDate.getDate() != date)     WScript.Echo("Invalid date"); else     WScript.Echo("Valid date"); 

This will echo "Invalid date" because presumedDate is actually March 1st.

This leaves all the trouble of leap years etc to the Date object, where I don't have to worry about it.

Neat trick, eh? Dirty, but that's scripting for you...

like image 24
Tor Haugen Avatar answered Oct 09 '22 13:10

Tor Haugen