时间的处理经常要用到,现在介绍一种通用的处理方式,能解决90%的需求:
注:第一个参数代表天数,0今天,1明天,-1昨天,以此类推
第二个参数代表距离当前时间的间隔,正数代表以后,负数代表以前
例:
// 当前时间2小时后的时间:
console.log(this.getDay(0, 7200000));
// 当前时间6小时后的时间:
console.log(this.getDay(0, 7200000*3));
<script>
// 获取 时间有关函数
getDay(day, hours) {
var today = new Date();
var targetday = today.getTime() + 1000 * 60 * 60 * 24 * day + hours;
today.setTime(targetday);
var tYear = today.getFullYear();
var tMonth = today.getMonth();
var tDate = today.getDate();
var hh = today.getHours();
var mf =
today.getMinutes() < 10
? "0" + today.getMinutes()
: today.getMinutes();
var ss =
today.getSeconds() < 10
? "0" + today.getSeconds()
: today.getSeconds();
tMonth = this.doHandleMonth(tMonth + 1);
tDate = this.doHandleMonth(tDate);
return (tYear + "-" + tMonth + "-" + tDate + " " + hh + ":" + mf + ":" + ss);
}
doHandleMonth(month) {
var m = month;
if (month.toString().length === 1) {
m = "0" + month;
}
return m;
}
</script>