js计算时间差

需求:在某个时间点后的N天后做某件事情
分析:1.计算某个时间点与今天当前时间的时间差(这里要考虑到计算时间差,如果时间格式化成字符串后计算,存在日切,年切的问题)
2.N天是需求中给出的一个时间,这里假设N=7天;某个时间点也是需求中给出的时间,是这样的格式:2018-01-2 15:59:07
3.根据上述条件,需要把时间转成毫秒值后,再计算时间差。过程如下:

function getDiff(oldTime){
  let status = false;
  let oneWeek = 604800000;//7天的毫秒值
  let fmt = oldTime.replace(new RegExp("-", "gm"), "/");
  console.log("把时间格式转变为可以转换毫秒值的日期格式 fmt == " + fmt);
  //获取指定时间的毫秒值,需要把时间格式转成此格式 2018/01/2 15:59:07
  let oldTime_fmt = (new Date(fmt)).getTime();
  console.log("把时间格式转变为毫秒值 oldTime_fmt == " + oldTime_fmt);
  //获取当前时间的毫秒值
  let nowTime = Date.now();
  console.log("当前的时间毫秒值 nowTime == " + nowTime);
  //计算时间差
  let diff = nowTime - oldTime_fmt;
  console.log("当前日期毫秒值与指定日期毫秒值的差 diff==" + diff);
  if(diff >= oneWeek){
    console.log("当前时间超过了7天范围")
    status = true;
  }else{
    console.log("当前时间在7天范围之内")
    status = false;
  }
  return status;
}

//可以在此函数中,验证是否存在日期年切问题
function test1(){
  var oneWeek = 604800000;//6 day
  var time = "2017-12-31 15:59:07";
  var fmt = time.replace(new RegExp("-","gm"),"/");
  console.log("fmt == "+fmt);
  var oldTime = (new Date(fmt)).getTime();
  var time ="2018-01-2 15:59:07";
 // var time ="2018-01-10 15:59:07";
  var fmt2 = time.replace(new RegExp("-","gm"),"/");
  console.log("fmt2 == "+fmt2);
  var nowTime = (new Date(fmt2)).getTime();
  console.log("nowTime == "+ nowTime);
  var diff = nowTime-oldTime;            
  console.log("diff=="+diff);
  if (diff >= oneWeek) {
    console.log("时间超过了7天")
  } else{
    console.log("时间在7天之内")
  } 
}

你可能感兴趣的:(js)