java Script 日期的加減 與 日期格式化

  • 1742
  • 0

摘要:java Script 日期的加減 與 日期格式化

 
///日期格式化
Date.prototype.format = function (format) {
        var date = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S+": this.getMilliseconds()
        };
        if (/(y+)/i.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in date) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1
                       ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
            }
        }
        return format;
    }
///日期的加減
    function GetDay(Day, AddDay) {
        var dayOfMonth = Day.getDate();
        Day.setDate(dayOfMonth + AddDay);
        return Day.format("yyyy-MM-dd");
    }
 
///使用方式
 GetDay(new Date(new date()),要加幾天(若要扣天數,直接填負數))