function GetDateStr(AddDayCount) {
var dd = new Date();
dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
var y = dd.getFullYear();
var m = dd.getMonth()+1;//获取当前月份的日期
var d = dd.getDate();
return y+"-"+m+"-"+d;
}
console.log("前天:"+GetDateStr(-2));
console.log("昨天:"+GetDateStr(-1));
console.log("今天:"+GetDateStr(0));
console.log("明天:"+GetDateStr(1));
console.log("后天:"+GetDateStr(2));
console.log("大后天:"+GetDateStr(3));
输出:
前天:2021-8-10
昨天:2021-8-11
今天:2021-8-12
明天:2021-8-13
后天:2021-8-14
大后天:2021-8-15
2.将时间戳转化成标准的时间格式
function format(timestamp) {
var time = new Date(timestamp);
var year = time.getFullYear();
var month = (time.getMonth() + 1) > 9 && (time.getMonth() + 1) || ('0' + (time.getMonth() + 1))
var date = time.getDate() > 9 && time.getDate() || ('0' + time.getDate())
var hour = time.getHours() > 9 && time.getHours() || ('0' + time.getHours())
var minute = time.getMinutes() > 9 && time.getMinutes() || ('0' + time.getMinutes())
var second = time.getSeconds() > 9 && time.getSeconds() || ('0' + time.getSeconds())
var YmdHis = year + '/' + month + '/' + date + ' ' + hour + ':' + minute + ':' + second;
return YmdHis;
}
console.log(format(1625068800000)); //2021/07/01 00:00:00
console.log(format(1625846400000)); //2021/07/10 00:00:00
方法二:
function getLocalTime(ns){
return new Date(parseInt(ns)*1000).toLocaleDateString().replace(/:\d{1,2}$/,' ');
};
console.log(getLocalTime(1568044800)); //2019/9/10