js的时间对象的简单封装,加减时间年月日及格式化
<script type="text/javascript">
//时间对象封装
function myDate(date){
this.date = this.stringToDate(date)
}
//字符串转时间对象
myDate.prototype.stringToDate = (str)=>{
str = str.replace(/[TZ]|\+08:00/g, ' ');
let arr = str.split(/[- : \/]/);
let date;
if(arr.length==3){
date = new Date(arr[0], arr[1] - 1, arr[2]);
}else{
date = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
}
return date;
}
//时间对象格式化
myDate.prototype.format = function(format){
let formats = ['yyyy','mm','dd','hh','ii','ss'];
format = format||'yyyy-mm-dd hh:ii:ss';
var data = {};
data["yyyy"] = this.date.getFullYear()+'';
data["mm"] = ('0'+ (this.date.getMonth() + 1)).substr(-2)
data["dd"] = ('0'+this.date.getDate()).substr(-2)
data["hh"] = ('0'+this.date.getHours()).substr(-2)
data["ii"] = ('0'+this.date.getMinutes()).substr(-2)
data["ss"] = ('0'+this.date.getSeconds()).substr(-2)
formats.forEach(v=>{
format = format.replace(v,data[v] )
})
return format;
}
//时间对象加减
myDate.prototype.addDate = function(Y,m,d){
this.date.setFullYear( this.date.getFullYear() + Y );
this.date.setMonth( this.date.getMonth() + m );
this.date.setDate( this.date.getDate() + d );
return this;
}
//工厂
function dateInstance(date){
return new myDate(date);
}
//举个栗子
var d = dateInstance("2016-02-14");//将字符串时间实例化myDate对象
d.addDate(3,10,10);//加3年10个月10天
console.log(d.format("yyyy-mm-dd"));//格式化输出2019-12-24
d.addDate(-3,-10,-10);//减3年10个月10天
console.log(d.format("yyyy-mm-dd"));//格式化输出2016-02-14
</script>