JS在某一时间上加1秒或1分钟
注意
- d : 字符串时间,格式为 yyyy-MM-dd HH:mm:ss
- num : 秒
- return : 返回 字符串 ,格式跟传入的相同
function dateAdd(d,num){
var d = new Date(d.substring(0,4),
d.substring(5,7)-1,
d.substring(8,10),
d.substring(11,13),
d.substring(14,16),
d.substring(17,19));
d.setTime( d.getTime() + num*1000);
return d.getFullYear() +"-"
+ this.checkTime((d.getMonth() + 1))
+ "-" + this.checkTime(d.getDate())
+ " " + this.checkTime(d.getHours())
+ ":" + this.checkTime(d.getMinutes())
+ ":" + this.checkTime(d.getSeconds());
}
例子:
var second = dateAdd( '2022-01-22 14:43:24',1 ); //加一秒钟
console.log( '加一秒'+second );
var minute = dateAdd( '2022-01-22 14:43:24',60 ); //加一秒钟
console.log( '加一分钟'+minute );
附:获取当前时间并显示秒表计时
checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
getNowTime() {
const date = new Date();
let year: string | number = date.getFullYear();
let month: string | number = this.checkTime(date.getMonth() + 1);
let strDate: string | number = this.checkTime(date.getDate());
let hours: string | number = this.checkTime(date.getHours());
let minutes: string | number = this.checkTime(date.getMinutes());
let seconds: string | number = this.checkTime(date.getSeconds());
return year + "-" + month + "-" + strDate + "" + hours + ":" + minutes + ":" + seconds;
}
setInterval(() => {
var second = this.dateAdd(this.getNowTime, 1); //加一秒钟
}, 1000);
over~~~