js 时间计算(加减天数、返回当前时间后一个星期的日期,返回格式yyyy-MM-dd)

时间:2023-02-18 16:36:21


<html>
<head><title>JS DATE</title></head>
<script type="text/javascript">
//返回7天前后的时间,格式 ‘yyyy-mm-dd’
function getNowFormatDate()
             {
                      var day = new Date();
                      var Year = 0;
                      var Month = 0;
                      var Day = 0;
                      var CurrentDate = "";
                      //初始化时间
                      //Year       = day.getYear();//有火狐下2008年显示108的bug
                      Year       = day.getFullYear();//ie火狐下都可以
                      Month      = day.getMonth()+1;
                      Day        = day.getDate();
                      CurrentDate += Year + "-";
                      if (Month >= 10 )
                      {
                      CurrentDate += Month + "-";
                       }
                      else
                    {
                    CurrentDate += "0" + Month + "-";
                      }
                  if (Day >= 10 )
                 {
                 CurrentDate += Day ;
                 }
                 else
                  {
                   CurrentDate += "0" + Day ;
                  }
                   return CurrentDate;
            }
function date2str(yy, mm, dd, prenext) {
    var s, d, t, t2;
    t = Date.UTC(yy, mm, dd);
    t2 = 7 * 1000 * 3600 * 24; //加减7天的时间
    if (prenext == 'pre') {
        t-= t2;
    } else {
        t+= t2;
    }
    d = new Date(t);

    s = d.getUTCFullYear() + "-";
    s += ("00"+(d.getUTCMonth()+1)).slice(-2) + "-";
    s += ("00"+d.getUTCDate()).slice(-2);

    return s;
}


function str2date(str, prenext){  
  var   dd, mm, yy;  
  var   reg = /^(/d{4})-(/d{1,2})-(/d{1,2})$/;
  if (arr = str.match(reg)) {
    yy = Number(arr[1]);
    mm = Number(arr[2])-1;
    dd = Number(arr[3]);
  } else {
    var d = new Date();
    yy = d.getUTCFullYear();
    mm = ("00"+(d.getUTCMonth())).slice(-2);
    dd = ("00"+d.getUTCDate()).slice(-2);
  }
 if (prenext == null || (prenext != 'pre' && prenext != 'next')) {
    var prenext = 'pre';
  }

  return  date2str(yy, mm, dd, prenext);
}  

alert(str2date(getNowFormatDate(), 'next'));

</script>

 

<body>

</body>
</html>