//new Date():系统当前时间,先将当前时间转化为时间戳的形式
var timestamp = Date.parse(new Date());
//想在系统当前时间基础上,想加的天数或小时
var dayNum = 天数;
var timeNum = 小时;
console.log('当前时间戳', timestamp, dayNum, timeNum)
//天数*24小时
timestamp = timestamp + (dayNum * 24) * 60 * 60 * 1000;
//小时*60分钟
timestamp = timestamp + (timeNum * 60) * 60 * 1000;
//转化成年月日 时分秒 的形式
var dayText = timeStamp.formatTime(timestamp, 'Y-M-D h:m:s')
console.log('下次提醒时间:',dayText)
时间戳转日期形式
代码展示:
function formatTime(number, format) {
var n = number;
var date = new Date(n);
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? ('0' + m) : m;
var d = date.getDate();
d = d < 10 ? ('0' + d) : d;
var h = date.getHours();
h = h < 10 ? ('0' + h) : h;
var minute = date.getMinutes();
var second = date.getSeconds();
minute = minute < 10 ? ('0' + minute) : minute;
second = second < 10 ? ('0' + second) : second;
return y + '-' + m + '-' + d + ' ' + h + ':' + minute+ ':'+ second;
}
module.exports = {
formatTime: formatTime
}
上面是添加日期最准确的方式,通过时间戳来转换
还有一种方式,就比较简陋,是直接在日期的基础上相加,这样会有误差
代码展示:
function getAnyDay(n) {
var nowDate = new Date();
nowDate = nowDate.setDate(nowDate.getDate() + n);
nowDate = new Date(nowDate);
var y = nowDate.getFullYear(),
m = nowDate.getMonth() + 1,
d = nowDate.getDate();
m = m < 10 ? '0' + m : m;
d = d < 10 ? '0' + d : d;
return y + '-' + m + '-' + d;
}
function getAnyHour(n) {
var nowDate = new Date();
nowDate = nowDate.setHours(nowDate.getHours() + n);
nowDate = new Date(nowDate);
var y = nowDate.getFullYear(),
m = nowDate.getMonth() + 1,
d = nowDate.getDate(),
h = nowDate.getHours(),
mi = nowDate.getMinutes(),
s = nowDate.getSeconds(),
m = m < 10 ? '0' + m : m;
d = d < 10 ? '0' + d : d;
h = h < 10 ? '0' + h : h;
mi = mi < 10 ? '0' + mi : mi;
s = s < 10 ? '0' + s : s;
return y + '-' + m + '-' + d + ' ' + h + ':' + mi + ':' + s;
}
module.exports = {
getAnyDay: getAnyDay,
getAnyHour: getAnyHour
}
引入文件:
var formate = require('../../../PublicFile/DayTime.js')
调用:
// var dayText = formate.getAnyDay(parseInt(visitArray.day));
// var timeText = formate.getAnyHour(parseInt(visitArray.time));
// dayText = dayText + ' ' + timeText.substr(11, 8)
不过,不建议用这种方式~,还是第一种用时间戳转换更为准确