zoukankan      html  css  js  c++  java
  • JavaScript(JS)计算某年某月的天数(月末)

    方法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()));
             }
    <input type="button" value="测试1" onclick="testCostTime(1)"/>
     <input type="button" value="测试2" onclick="testCostTime(2)"/>

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

  • 相关阅读:
    运行jar包中的main方法
    (转)如何判断VPS是基于哪种虚拟技术?Xen、OpenVZ、Xen HVM、KVM还是VMware
    centos安装redis
    Jmeter性能测试
    Jmeter脚本录制
    【Tomcat】Tomcat安装及Eclipse配置教程
    【接口测试】【SOAP】简单的接口测试学习
    JMeter性能测试,完整入门篇
    monkey命令详解
    APP专项测试
  • 原文地址:https://www.cnblogs.com/hdwang/p/7339351.html
Copyright © 2011-2022 走看看