JS获取当前时间前7天日期、后7天日期、获取任意时间

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>日期操作</title>
    <script>
        function getDate(){
         var date = new Date();
         var base = new Date(date).getTime();
         var oneDay = 24 * 3600 * 1000;
         var date = [];
         var data = [Math.random() * 300];
         var time = new Date(base);
         date.push([time.getFullYear(), time.getMonth() + 1, time.getDate()].join('/'));
         for (var i = 1; i <7; i++) {//控制需要的天数
             var now = new Date(base -= oneDay); //这里控制往前一周还是往后一周
             date.push([now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'));
             data.push(Math.round((Math.random() - 0.5) * 20 + data[i - 1]));
         }
         var newdate = date.reverse(); //往后一周的话需要将数组倒叙,完后不需要
         console.log(newdate);
         console.log(newdate[0]);//需要哪天直接下标取就行了

          //数据插入table显示,可忽略
          var str = "";
          for (let i = 0; i < newdate.length; i++) {
              str += '' + newdate[i] + '
'
; }; console.log(str); document.getElementById("time").innerHTML = str;//拼接完字符串数组后用innerHTML把它渲染到页面中 } </script> </head> <body> <button id="Timer" onclick="getDate()">获取任意时间(此处获取前7天时间)</button> <table id="time"> </table> </body> </html>

转载请注明转自:https://leejason.blog.csdn.net/article/details/106808647

你可能感兴趣的:(Web开发)