Java求某一年的某一月的天数_[Java教程]计算某年某月的天数(月末)

本文介绍了两种Java方法来计算某一年的某一月的天数,包括基于switch-case的实现和Date对象操作的实现。通过性能测试,方法1在效率上显著优于方法2,建议在实际应用中选择方法1。文章提供了测试代码并分享了相关网址。
摘要由CSDN通过智能技术生成

[Java教程]计算某年某月的天数(月末)

0

2017-08-10 15:00:08

方法1/** * 获取某年月的天数 * @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())); }

进行10万次调用测试后,方法1耗时为0-1毫秒,方法2耗时为38-41毫秒。所以建议使用方法一,进行计算年月的天数。

本文网址:http://www.shaoqun.com/a/320920.html

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:admin@shaoqun.com。

0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值