javascript - 坚持在 JavaScript 中递增日期

标签 javascript jquery html date increment

我正在尝试创建一个页面来抓取一组按日期排序的 PDF。我似乎无法正确增加日期。我不确定这里出了什么问题。我现在重写了两次代码。没有运气。

当前的问题是日期的设置变量没有保留整个日期的值。 IE 从 12、31、2018 递增,或者在 URL 格式 20181231 的情况下,结果应该是 urlIncremented=20190101。 2019 年 1 月 1 日,但我的代码的结果是 urlIncremented=20181232

如果设置为 2018 年 6 月 8 日,一个循环的最终结果应该是:url20180608

我在这里搜索了建议,找到了一个名为 Date.JS 的 JS 文件;我已经导入了它,它看起来很有前途,但只是安慰了它的一部分代码,即:

function () {
   if (this._isSecond) {
        this._isSecond=false;
        return this;
   }
   if (this._same) {
        this._same=this._is=false;
        var o1=this.toObject(),
            o2=(arguments[0] || new Date()).toObject(), 
            v="",
            k=j.toLowerCase();
        for (var m=(px.length-1); m>-1; m--) { 
            v=px[m].toLowerCase();
            if (o1[v]!=o2[v]) { 
                return false;
            }
            if (k==v) { 
                break;
            }
        }
        return true;
   }
   if (j.substring(j.length-1)!="s") { 
       j+="s";
   }
   return this["add"+j](this._orient);
}

请注意,我还不知道 jQuery,我只是在玩它看看它是否有帮助..

这是我的实际代码。

 let url = "blank",
        firstRun = true;
    
    /* 
    function setDateByIncrement(currentSetDate){
      let newDate,
          currentDate = new Date(),
          day = currentDate.getDate()+1,
          month = currentDate.getMonth() + 1,
          year = currentDate.getFullYear();
    
      console.log(newDate);
      newDate = (year+month+day);
      console.log(newDate);
      return newDate;
    }
    */
    
    // use on First run to set the url and date.
    //3
    function setURL(){
      let urlIncremented = url + dateIncrementMethod();
      return urlIncremented;
    }
    
    // will open x number of new windows containing URL
    //2
    function grabOpenPDF(maxNumberDays){
      let urlSet = setURL();
      
      //Set the variable for max days.
      for(let x = 0; x < maxNumberDays; x++){
        //window.open(urlSet);
        console.log("It works: " + x);
        urlSet = setURL();
      }
    }
    
    /* TODO Add automatic download for MASS print.
    function downloadPDF(){
      
    }
    */
    
    //Starts the task. 
    //1
    function start(load){
      console.log("Current Address: " + url);
      if(load === 1){
        console.log("Event load active. ");
        let maxDay = document.querySelector('#maxNumberDays').value;;
        grabOpenPDF(maxDay);
      }else{
        console.log("Event load skip. ")
        let maxDay = document.getElementById('maxNumberDays').value;
        
      }
    }
    
    //4
    function dateIncrementMethod(current){
      let dateIncrement;
      if(firstRun=== true){
        var today = new Date($('#date-input').val());
        console.log("FirstRun check in 4. ")
      }
      firstRun = false;
      
      var tomorrow = today.add(1).day;
      console.log(tomorrow);
      
      return tomorrow;
    }
      /* Possibly Deprecated  
      //let dateIncrement;
          let date = new Date($('#date-input').val());
          console.log(date);
          day = date.getDate() + 1;
      if(firstRun === true){
          month = date.getMonth() + 1;
          year = date.getFullYear();
          //dateIncrement = (parseToAPI(year, month, day));
          firstRun = false;
          parseToAPI(year, month, day);
        }else{
          day = date.getDate()+1;
          parseToAPI(year, month, day);
        }
    }
    */
    function parseToAPI(year, month, day){
      let apiDate;
      console.log("Entered parse");
      this.day = day;
      this.month = month;
      let d = this.day.toString(),
          m = this.month.toString();
          if(d.length === 1){
            console.log("Entered First IF");
            this.day = ('0') + day;
            //console.log(day);
          }
          if(m.length === 1){
            console.log("Entered Second IF")
            this.month = ('0') + month;
          }
      apiDate = (year + "" + "" + month + "" + day);
      console.log(apiDate);
      return apiDate;
    }
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-2.0.3.js"></script>
<script src="https://doc-0k-6g-docs.googleusercontent.com/docs/securesc/77gdpvi38k94jj7nmfcm2n3tq7a0ifhu/ehjuusajghqnne5r2ncfvj30cmbll20p/1545105600000/17500114768188980350/17500114768188980350/1CDff-uWGahZX7aLt6WQfV1-R5PFHwiK8?e=download&nonce=52qkphatg2scm&user=17500114768188980350&hash=3uc9iql9m90vcrv3a7mhg8fdjce1b4fe.js"></script>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
</head>
<body>
    <input type="date" id="date-input" required />
        <input type="maxNumberDays" id="maxNumberDays" max="31" required />
        <button id="startPDFApp" onClick="start()">Print PDFs</button>
        <button id="startPDFApp" onClick="start(1)">Load PDFs</button>
        <div id="info"></div>
    </body>
</html>

最佳答案

虽然我没有投入足够的时间来理解您真正想要做什么,但似乎有很多不必要的代码。我会把它留给你来破译你需要什么。

我只能表示下面的代码处于中间状态。它包括许多更改,我会指出其中的大部分更改,但我不想更改得太彻底以至于看起来很陌生。因此,即使是下面的代码也有很多需要改进的地方。

重大变化包括:

  1. 因为您的 URL 递增 1,您可能会受益于使用函数生成器。在内部,它通过调用 setDate 使用自己的日期 + 1 来增加日期。它还使用字符串函数 padStart,以确保月份和日期始终为两位数.

  2. 摆脱不再需要的 firstRun 变量

  3. 在您的 grabOpenPDF 中,您需要做的就是获取 URL 生成器函数返回的下一个值

let URL_GEN = UrlGenerator('blank'),
  URL = URL_GEN.next().value;


//Starts the task. 
//1
function start(load) {
  let startDate = new Date(document.querySelector('#date-input').value)
  
  // overwrite global with values
  URL_GEN = UrlGenerator('blank', startDate)
  URL = URL_GEN.next().value
  
  console.log("Current Address: " + URL);
  if (load === 1) {
    console.log("Event load active.");
    let maxDay = document.querySelector('#maxNumberDays').value;
    grabOpenPDF(maxDay);
  } else {
    console.log("Event load skip.")
    let maxDay = document.getElementById('maxNumberDays').value;
  }
}

/* URL generator */
function* UrlGenerator(url, dt=new Date()) {
  while (true){
    yield url + dt.getFullYear() + (''+(dt.getMonth()+1)).padStart(2,'0') + (''+dt.getDate()).padStart(2,'0');
    
    // increase day for next iteration
    dt.setDate(dt.getDate()+1);
  }
}


// will open x number of new windows containing URL
function grabOpenPDF(maxNumberDays) {

  //Set the variable for max days.
  for (let i=0; i < maxNumberDays; i++) {
    console.log("It works: " + i, URL);
    URL = URL_GEN.next().value;
  }
}
<script src="https://doc-0k-6g-docs.googleusercontent.com/docs/securesc/77gdpvi38k94jj7nmfcm2n3tq7a0ifhu/ehjuusajghqnne5r2ncfvj30cmbll20p/1545105600000/17500114768188980350/17500114768188980350/1CDff-uWGahZX7aLt6WQfV1-R5PFHwiK8?e=download&nonce=52qkphatg2scm&user=17500114768188980350&hash=3uc9iql9m90vcrv3a7mhg8fdjce1b4fe.js"></script>
<input type="date" id="date-input" value="12/29/2018" required />
<input type="maxNumberDays" id="maxNumberDays" value="5" max="31" required />
<button id="startPDFApp" onClick="start()">Print PDFs</button>
<button id="startPDFApp" onClick="start(1)">Load PDFs</button>
<div id="info"></div>

这可以通过更好地管理您的全局变量、更直接的代码(更简单的布局)以及可能更好的命名约定来进一步改进。此外,现在将事件处理程序直接放在 HTML 中通常是一种禁忌,您可以通过 JavaScript 动态绑定(bind)这些事件。

关于javascript - 坚持在 JavaScript 中递增日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53827052/

相关文章:

JavaScript 正则表达式不替换 '@' 字符

javascript - Angular 2 将数据传递到 for 循环中

php - MySQL PHP jQuery - 行不更新?

javascript - 拖动一个 jqueryUI 可拖动元素触发拖动其他多个元素

javascript - 如何考虑当旁边的用户名太长时自动加宽搜索字段的脚本

jquery - 根据 Jquery 中的 ID 隐藏 child

html - 将多个元素与父元素的底部对齐

javascript - 通过索引分配属性的最佳方法是什么

javascript - 如何将 JSON 内容放入 <ul> 标签并在 HTML 中形成

javascript - 使用 node.destroy() 时如何删除 konva 形状/图像