js實現時間的加減運算

 let date1 = new Date('2020-04-01 17:29:30')
 let dateTemp = date1.setHours(date1.getHours() + 5 )  //增加5個小時
 let dateTemp = date1.setDate(date1.getDate() + 7 )   //增加7天
 let dateTemp = date1.setMonth(date1.getMonth() + 1 )   //增加1個月
 let dateTemp = date1.setFullYear(date1.getFullYear() + 1 )   //增加1年

let time2 = new Date(dateTemp).format("yyyy-MM-dd hh:mm:ss")
		Date.prototype.format = function(fmt) { 
			var o = { 
			   "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+)/.test(fmt)) {
				   fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
		   }
			for(var k in o) {
			   if(new RegExp("("+ k +")").test(fmt)){
					fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
				}
			}
		   return fmt; 
	   }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章