這裏寫自定義目錄標題
使用js實現日期加減
使用js實現日期年月日的加減,自動處理閏年:
function setDateTest() {
addOrReduceDate("D","2019-6-15 14:45:16","5");
}
// type:年、月或者日
// data:日期
// 加減量
function addOrReduceDate(type,date,num) {
var nowDate = null;
var strDate = "";
num = parseInt(num); // 防止傳入字符串報錯
var seperator1 = "-";
var seperator2 = ":";
if(date == "") {
nowDate = new Date();
} else {
nowDate = new Date(date);
}
if(type==="Y"){
nowDate.setFullYear(nowDate.getFullYear() + num);
}
if(type==="M"){
nowDate.setMonth(nowDate.getMonth() + num);
}
if(type==="D"){
nowDate.setDate(nowDate.getDate() + num);
}
if(type==="A"){
nowDate.setFullYear(nowDate.getFullYear() + num);
nowDate.setMonth(nowDate.getMonth() + num);
nowDate.setDate(nowDate.getDate() + num);
}
var year = nowDate.getFullYear(); // 年
var month = nowDate.getMonth() + 1; // 月
strDate = nowDate.getDate(); //日
var hours = nowDate.getHours(); // 時
var minutes = nowDate.getMinutes(); // 分
var seconds = nowDate.getSeconds(); // 秒
if(month >= 1 && month <= 9) {
month = "0" + month;
}
if(strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
if(seconds >= 0 && seconds <= 9) {
seconds = "0" + seconds;
}
var dateStr = year + seperator1 + month + seperator1 + strDate + " " + hours + seperator2 + minutes + seperator2 + seconds;
console.log(dateStr)
return dateStr;
}