验证给定月份的天数 [英] Validate number of days in a given month
问题描述
性能对这一个人来说至关重要......这件事需要快速闪电!
您如何验证特定月份的天数?
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.
];
然后做一些事情:
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:
(来源: about.com )
推荐答案
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);
}
这篇关于验证给定月份的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!