关于时间处理(更新中)

重大提示,js的Date会处理很多数值越界的情况,比如xx.setDate(0),内部会有容错机制,所以我下面写的某些方法完全没有意义


判断某年是否为闰年:

function isLeapYear(year) {

    if (typeof year !== 'number') {

        year = parseInt(year, 10);

    }

    if (year === NaN) return false;

    

    if ((year % 400 === 0) || (year % 100 !== 0) && (year % 4 === 0) ) {

        return true;

    } else {

        return false;

    }

}


一年前的今天:

function oneYearBefore() {

    var today = new Date(),

        year = today.getFullYear(),

        month = today.getMonth(),

        day = today.getDate();

    year--;

    // 如果今天是 xxxx-02-29

    if (month === 1 && day === 29) {

        month = 2;

        day = 1;

    }

    today.setFullYear(year);

    today.setMonth(month);

    today.setDate(day);

    return today;

}

更简单的方式是:

var today = new Date();

today.setFullYear(today.getFullYear() - 1);

  


昨天:

function yesterday() {

    var ret = new Date(),

        year = ret.getFullYear(),

        month = ret.getMonth(),

        day = ret.getDate();

    

    // 今天是元旦

    if (month === 0 && day === 1) {

        year--;

        month = 11;

        day = 31;

    // 今天是每月的第一天

    } else if (day === 1) {

        month--;

        // 上个月的最后一天

        if (month === 1 || month === 3 || month === 5 || 

            month === 7 || month === 8 || month === 10 ||

            month === 12) {

            day = 31;

        } else if (month === 4 || month === 6 || 

                    month === 9 || month === 11) {

            day = 30;

        } else {

            // 2月

            if (isLeapYear(year)) {

                day = 29;

            } else {

                day = 28;

            }

        }

    } else {

        day--;

    }

    

    ret.setFullYear(year);

    ret.setMonth(month);

    ret.setDate(day);

    return ret;

}

更简单的方式是:

var today = new Date();

today.setDate(today.getDate() - 1);

  

你可能感兴趣的:(时间)