JavaScript(JS)计算某年某月的天数(月末)
2017-08-10 14:58
393 查看
方法1
方法2
经过测试第一个方法效率明显高出不少。
测试代码
进行10万次调用测试后,方法1耗时为0-1毫秒,方法2耗时为38-41毫秒。所以建议使用方法一,进行计算年月的天数。
/** * 获取某年月的天数 * @param year 年 * @param month 月(0-11) * @returns {number} 天数 */ var getDaysOfMonth = function (year, month) { month = month + 1; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; case 4: case 6: case 9: case 11: return 30; case 2: return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? 29 : 28; default: return 0; } };
方法2
/** * 获取某年月的天数 * @param year 年 * @param month 月(0-11) * @returns {number} 天数 */ var getDaysOfMonth2 = function (year, month) { month++; if (month > 11) { month = 0, year++; } return new Date(new Date(year, month, 1).getTime() - 1000 * 3600 * 24).getDate(); };
经过测试第一个方法效率明显高出不少。
测试代码
var testCostTime = function (method) { var d1 = new Date(); if(method==1){ for(var i=0;i<100000;i++){ getDaysOfMonth(2017,1); } }else{ for(var i=0;i<100000;i++){ getDaysOfMonth2(2017,1); } } console.log('cost time:'+(new Date().getTime()-d1.getTime())); }
<input type="button" value="测试1" onclick="testCostTime(1)"/> <input type="button" value="测试2" onclick="testCostTime(2)"/>
进行10万次调用测试后,方法1耗时为0-1毫秒,方法2耗时为38-41毫秒。所以建议使用方法一,进行计算年月的天数。
相关文章推荐
- javascript计算某年某月的天数
- 如何用JS计算某年某月天数(如2015年2月共有28天)
- javascript日期比较 js日期相差天数计算
- 获取某年某月天数(js)
- 作业一:计算某年某月到某年某月的天数
- JS获取某年某月的总天数
- 求用JAVA计算某年某月的天数?(两种方法)
- 计算某年某月工作天数
- 计算某年、某月、某日和某年、某月、某日之间的天数间隔。要求年、月、日通过键盘输入传递到程序中。
- js获取某年某月天数
- c++的万年历类,支持显示某月月历与某年年历,支持计算任意两个日期的间隔天数
- <Javascript>js 计算日期相隔天数
- 【javaScript】获取某年某月的的最后一天(即当月天数) 妙用
- javascript、js计算两个日期之间的天数
- 1073 计算某年某月的天数
- js获取某年某月一共多少天
- js 当前日期 格式 Javascript 对时间的代号 日期计算
- PHP 如何得到某年某月的天数
- js计算两个时间之间天数差的实例代码
- js中日期和天数 计算新日期