時間物件的封裝

品讀夜的黑發表於2016-04-01
<script type="text/javascript">  
 
    //時間物件封裝
    function myDate2(date){
        this.date = new Date(date);
        this.Y = function(){
            return this.date.getFullYear();
        }
        this.m = function(){
            var m = (this.date.getMonth()+1).toString();
            if(m.length==1) return "0"+m;
            return m;
        }
        this.d = function(){
            var d = this.date.getDate().toString();
            if(d.length==1) return "0"+d;
            return d;
        }
    }
 
    //時間物件格式化
    myDate2.prototype.Format = function(format){
        if(format=="yyyy"){
            return this.Y();
        }else if(format=="yyyy-mm"){
            return this.Y()+"-"+this.m();
        }else if(format=="yyyy-mm-dd"){
            return this.Y()+"-"+this.m()+"-"+this.d();
        }
        throw new error("非法的格式");
    }
 
    //時間物件加減
    myDate2.prototype.AddDate = function(Y,m,d){
        this.date.setFullYear(parseInt(this.Y())+Y);
        this.date.setMonth(parseInt(this.m())+m-1);
        this.date.setDate(parseInt(this.d())+d);
        return this;
    }
 
    //工廠
    function myDate(date){
        return new myDate2(date);
    }
 
    //舉個例子
    var d = myDate("2016-02-14");//將字串時間例項化myDate2物件
    d.AddDate(0,0,10);//加10天
    console.log(d.Format("yyyy-mm-dd"));//格式化輸出2016-02-24
</script>

相關文章