JS获取当前日期的前天、昨天、今天、明天、后天、大后天、前n天和后n天的日期

1.如何获取当前日期的前n天,后n天的日期

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<10?'0'+m:m)+'-'+d;
}
console.log('前天:',getDateStr(-2)); // 前天: 2018-09-11
console.log('昨天:',getDateStr(-1)); // 昨天: 2018-09-12
console.log('今天:',getDateStr(0));  // 今天: 2018-09-13
console.log('明天:',getDateStr(1));  // 明天: 2018-09-14
console.log('后天:',getDateStr(2));  // 后天: 2018-09-15

2.获取当天的日期

/**
 *获取当前时间
 *format=1精确到天
 *format=2精确到分
*/
function getCurrentDate(format) {
  var now = new Date();
  var year = now.getFullYear(); //得到年份
  var month = now.getMonth();//得到月份
  var date = now.getDate();//得到日期
  var day = now.getDay();//得到周几
  var hour = now.getHours();//得到小时
  var minu = now.getMinutes();//得到分钟
  var sec = now.getSeconds();//得到秒
  month = month + 1;
  if (month < 10) month = "0" + month;
  if (date < 10) date = "0" + date;
  if (hour < 10) hour = "0" + hour;
  if (minu < 10) minu = "0" + minu;
  if (sec < 10) sec = "0" + sec;
  var time = "";
  //精确到天
  if(format==1){
  time = year + "-" + month + "-" + date;
  }
  //精确到分
  else if(format==2){
  time = year + "-" + month + "-" + date+ " " + hour + ":" + minu + ":" + sec;
  }
  return time;
}
getCurrentDate(2); // 2018-09-14 19:31:19

 

你可能感兴趣的:(JavaScript)