代码之家  ›  专栏  ›  技术社区  ›  JMon

使用Javascript为datepicker获取从今天开始的日期数组

  •  1
  • JMon  · 技术社区  · 8 年前

    我试图编写一个函数,返回从今天到最长日期的日期数组,以便限制日期选择器的选择。目前,我有以下信息:-

       datesAfterToday: function (date) {
        var dates = []
        var currentDate = new Date()
        var endDate = new Date(8640000000000000).getFullYear()
        var addDays = function (days) {
          var date = new Date(this.valueOf())
          date.setDate(date.getDate() + days)
          return date
        }
        while (currentDate <= endDate) {
          dates.push(currentDate)
          currentDate = addDays.call(currentDate, 1)
        }
        return dates
      }
    

    然后我使用Vue。js安装如下:-

     mounted () {
       this.allowedDates = this.datesAfterToday
     },
    

    然而,我只得到了一个对象数组,而不是正确的数组。

    如何获得正确的日期数组,以便将其绑定到allowdates属性。

    谢谢你的帮助和时间!

    2 回复  |  直到 8 年前
        1
  •  1
  •   Khauri    8 年前

    对于初学者 new Date(8640000000000000).getFullYear() 将设置 endDate 275760 . currentDate将是今天的日期(毫秒),在我写作时是 1511272934156 . 正如您所见,currentDate总是大于endDate,因此您的while循环从不转到内部语句。

    另一个问题是,您选择的日期实在是太遥远了,您每天都要填充一个数组。您的循环很可能会使页面冻结或完全崩溃。试着选择一个更容易管理的日期。

    例如,在下面的代码片段中,我设置了 实际结束 首先将其初始化为今天,然后将年份设置为从现在起整整一年。这给了我一个大约有365个值的数组。

    你可以想象,如果我用未来273748年的时间,这个数组会有多大。

    var dates = []
    var currentDate = new Date()
    var endDate = new Date()
    
    endDate.setFullYear(endDate.getFullYear()+1)
    
    var addDays = function (days) {
      var date = new Date(this.valueOf())
      date.setDate(date.getDate() + days)
      return date
    }
    
    while (currentDate <= endDate) {
      dates.push(currentDate)
      currentDate = addDays.call(currentDate, 1)
    }
        
    console.log(dates)

    综上所述,看起来您实际上可以传递一个指定最小值和最大值的对象,而不是一个数组。

    https://vuetifyjs.com/components/pickers#example-6

    let d = new Date()                  // today
    let d2 = new Date()    
    d2.setFullYear(date.getFullYear()+1) // Next year
    
    this.allowedDays = {
        min : d.toISOString().substr(0, 10), // e.g. 2017-11-21
        max : d2.toISOString().substr(0, 10)
    }
    
        2
  •  0
  •   Tim Hutchison    8 年前

    另一种选择是使用 vuejs-datepicker 例如:

    <script>
    var state = {
        disabled: {
            to: new Date(), // Disable all dates up to specific date
            from: new Date(8640000000000000) // Disable all dates after specific date        
        }
    }
    </script>
    
    <datepicker :disabled="state.disabled"></datepicker>
    

    看见 Disabled Dates 在文档中。