Reputation: 21727
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)
Upvotes: 29
Views: 26805
Reputation: 4795
Other solution:
// monthIndex: 0:jan, 11: dic
function daysInMonth (monthIndex, year) {
if (monthIndex ==1) // february case
return (year % 4 == 0 && year % 100) || year % 400 == 0 ? 29 : 28
const monthsWith30days = [3, 5, 8, 10]
return monthsWith30days.includes(monthIndex) ? 30 : 31
}
// testing
const year = new Date().getFullYear()
for (let m=0; m < 12; m += 1) {
console.log(`year ${year} month ${m} has ${daysInMonth(m, year)} days`)
}
OUTPUT
'year 2022 month 0 has 31 days'
'year 2022 month 1 has 28 days'
'year 2022 month 2 has 31 days'
'year 2022 month 3 has 30 days'
'year 2022 month 4 has 31 days'
'year 2022 month 5 has 30 days'
'year 2022 month 6 has 31 days'
'year 2022 month 7 has 31 days'
'year 2022 month 8 has 30 days'
'year 2022 month 9 has 31 days'
'year 2022 month 10 has 30 days'
'year 2022 month 11 has 31 days'
Upvotes: 0
Reputation: 4795
The days of each month are known easily by exception of February for detail of leap years:
I leave an implementation based on the algorithm that solves this problem:
if (year is not divisible by 4) then (it is a common year)
else if (year is not divisible by 100) then (it is a leap year)
else if (year is not divisible by 400) then (it is a common year)
else (it is a leap year)
/**
* Doc: https://en.wikipedia.org/wiki/Leap_year#Algorithm
* param : month is indexed: 1-12
* param: year
**/
function daysInMonth(month, year) {
switch (month) {
case 2 : //Febrary
if (year % 4) {
return 28; //common year
}
if (year % 100) {
return 29; // leap year
}
if (year % 400) {
return 28; //common year
}
return 29; // leap year
case 9 : case 4 : case 6 : case 11 :
return 30;
default :
return 31
}
}
/** Testing daysInMonth Function **/
$('#month').change(function() {
var mVal = parseInt($(this).val());
var yVal = parseInt($('#year').val());
$('#result').text(daysInMonth(mVal, yVal));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Year</label>
<input type='number' id='year' min='1000' max='2500'>
<label>month</label>
<input type='number' id='month' min='1' max='12'>
<h1>
days: <span id='result' style='color:#E650A0'></span>
</h1>
Upvotes: 1
Reputation: 546263
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);
}
Upvotes: 66
Reputation: 93601
In computer terms, new Date()
and regular expression
solutions are slow! If you want a super-fast (and super-cryptic) one-liner, try this one (assuming m
is in Jan=1
format):
The only real competition for speed is from @GitaarLab, so I have created a head-to-head JSPerf for us to test on: http://jsperf.com/days-in-month-head-to-head/5
I keep trying different code changes to get the best performance.
Current version
After looking at this related question Leap year check using bitwise operators (amazing speed) and discovering what the 25 & 15 magic number represented, I have come up with this optimized hybrid of answers:
function getDaysInMonth(m, y) {
return m===2 ? y & 3 || !(y%25) && y & 15 ? 28 : 29 : 30 + (m+(m>>3)&1);
}
JSFiddle: http://jsfiddle.net/TrueBlueAussie/H89X3/22/
JSPerf results: http://jsperf.com/days-in-month-head-to-head/5
For some reason, (m+(m>>3)&1)
is more efficient than (5546>>m&1)
on almost all browsers.
It works based on my leap year answer here: javascript to find leap year this answer here Leap year check using bitwise operators (amazing speed) as well as the following binary logic.
A quick lesson in binary months:
If you interpret the index of the desired months (Jan = 1) in binary you will notice that months with 31 days either have bit 3 clear and bit 0 set, or bit 3 set and bit 0 clear.
Jan = 1 = 0001 : 31 days
Feb = 2 = 0010
Mar = 3 = 0011 : 31 days
Apr = 4 = 0100
May = 5 = 0101 : 31 days
Jun = 6 = 0110
Jul = 7 = 0111 : 31 days
Aug = 8 = 1000 : 31 days
Sep = 9 = 1001
Oct = 10 = 1010 : 31 days
Nov = 11 = 1011
Dec = 12 = 1100 : 31 days
That means you can shift the value 3 places with >> 3
, XOR the bits with the original ^ m
and see if the result is 1
or 0
in bit position 0 using & 1
. Note: It turns out +
is slightly faster than XOR (^
) and (m >> 3) + m
gives the same result in bit 0.
JSPerf results: http://jsperf.com/days-in-month-perf-test/6
Upvotes: 4
Reputation: 30996
Have you tried moment.js?
The validation is quite easy to use:
var m = moment("2015-11-32");
m.isValid(); // false
I don't know about the performances but hum the project is stared 11,000+ times on GitHub (kind of a quality guarantee).
Source: http://momentjs.com/docs/#/parsing/is-valid/
Upvotes: 4
Reputation: 8167
function caldays(m,y)
{
if (m == 01 || m == 03 || m == 05 || m == 07 || m == 08 || m == 10 || m == 12)
{
return 31;
}
else if (m == 04 || m == 06 || m == 09 || m == 11)
{
return 30;
}
else
{
if ((y % 4 == 0) || (y % 400 == 0 && y % 100 != 0))
{
return 29;
}
else
{
return 28;
}
}
}
Upvotes: 5
Reputation: 719
You can use DateTime to solve this:
new DateTime('20090901')->format('t'); // gives the days of the month
Upvotes: 0
Reputation: 146559
all this logic is already built in to the javascript engine... Why recode it ? Unless you are doing this just as an exercise, you can use the javascript Date object:
Like this:
function daysInMonth(aDate) {
return new Date(aDate.getYear(), aDate.getMonth()+1, 0).getDate();
}
Upvotes: 3
Reputation: 171511
This will not perform as well as the accepted answer. I threw this in here because I think it is the simplest code. Most people would not need to optimize this function.
function validateDaysInMonth(year, month, day)
{
if (day < 1 || day > 31 || (new Date(year, month, day)).getMonth() != month)
throw new Error("Frack!");
}
It takes advantage of the fact that the javascript Date constructor will perform date arithmetic on dates that are out of range, e.g., if you do:
var year = 2001; //not a leap year!
var month = 1 //February
var day = 29; //not a valid date for this year
new Date(year, month, day);
the object will return Mar 1st, 2001 as the date.
Upvotes: 6
Reputation: 35061
Assuming the JS Date object standard where months are numbered from 0, and you have your daysInMonth array:
var days = daysInMonth[month] + ((month === 1) && (year % 4 === 0) && ((year % 100 !== 0) || (year % 400 === 0)));
will give you the number of days in the month, with 28 increased to 29 iff the month is February and the year is a leap year.
Upvotes: 2
Reputation: 44804
I'm mostly agreeing w/ Moayad. I'd use a table lookup, with an if check on February and the year.
pseudocode:
Last_Day = Last_Day_Of_Month[Month];
Last_Day += (Month == February && Leap_Year(Year)) ? 1 : 0;
Note that Leap_Year() can't be implemented simply as (Year % 4 == 0)
, because the rules for leap years are way more complex than that. Here's an algorithm cribbed from Wikipedia
bool Leap_Year (int year) {
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
Upvotes: 3
Reputation: 19627
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...
Upvotes: 15
Reputation: 27509
I agree with Moayad and TED. Stick with the lookup table unless the month is February. If you need an algorithm for checking leap years, wikipedia has two:
if year modulo 400 is 0 then leap
else if year modulo 100 is 0 then no_leap
else if year modulo 4 is 0 then leap
else no_leap
A more direct algorithm (terms may be grouped either way):
function isLeapYear (year):
if ((year modulo 4 is 0) and (year modulo 100 is not 0)) or (year modulo 400 is 0)
then true
else false
Upvotes: 3
Reputation: 7341
If the month isn't February, get the number from the array. Otherwise, check if the year is leap to return 29, or return 28. Is there a problem with that?
Upvotes: 5