js中获取昨天今天明天的时间

不管是前端还是后台,甚至是数据库中,都会经常频繁的获取各种时间,今天整理了一下在javascript中获取时间,就当作一个笔记记录一下-_-

var day = new Date();

获取昨天时间:


day1.setTime(day.getTime() - 24 * 60 * 60 * 1000);

var s1 = day1.getFullYear() + "-" + (day1.getMonth() + 1) + "-" + day1.getDate();

console.log(s1);//2018-11-29

获取一周前的时间:


day7.setTime(day.getTime() - 7 * 24 * 60 * 60 * 1000);
var _m7 = day7.getMonth() + 1;
var _d7 = day7.getDate();

if (_m7.toString().length == 1) {
    _m7 = '0' + _m7; //个位数补个0 ,如7 => 07
}

if (_d7.toString().length == 1) {
    _d7 = '0' + _d7; //个位数补个0 ,如7 => 07
}

var s7 = day7.getFullYear() + "-" + _m7 + "-" + _d7;
console.log(s7);//2018-11-23

获取明天的时间

day3.setTime(day.getTime() + 24 * 60 * 60 * 1000);
var s3 = day3.getFullYear() + "-" + (day3.getMonth() + 1) + "-" + day3.getDate();
console.log(s3);//2018-12-1

获取今天的时间


day2.setTime(day.getTime());
var _m = day2.getMonth() + 1;
var _d = day2.getDate();

if (_m.toString().length==1){
    _m = '0' + _m;
}

if (_d.toString().length == 1) {
    _d = '0' + _d;
}

var s2 = day2.getFullYear() + "-" + _m + "-" + _d;
console.log(s2);//2018-11-30

你可能感兴趣的:(js中获取昨天今天明天的时间)