2017-07-03 65 views
0

我正在建立一個使用JavaScript(Vue JS)的日曆。我有這個小方法來幫助獲得當月的日子:JS日曆短兩天

daysInYearMonth(y,m){ 
    return new Date(y, m, 0).getDate() 
} 

如果我console.log上面我得到31,因爲它是七月。但是,當它使用這個值時:

this.days = [...Array(this.daysInYearMonth(this.year, 
    this.month)).keys()] 
} 

我console.log this.days並得到29天,兩個短。如果我只是嘗試添加兩個,那麼其他幾個月就關閉了。這是我的CodePen

注意:我故意不使用Moment.js,儘管我同意它更好,但團隊決定只使用Vue和vanilla JS。

+0

在此處發佈您的代碼,而不僅僅是在遠程站點。您可以使用[Stack Snippets](https://stackoverflow.blog/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/)使其可執行。 – Barmar

+0

@Barmar我相信這是所有相關的代碼。但是我確實看到了讓代碼在問題中可執行的價值,所以如果鏈接變壞,它仍然有價值。我會創建一個片段,我不知道這個功能,謝謝! – Auzy

+1

'new Date()。getMonth()'今天是6.並且Array(x)將基於零。 – Bert

回答

0

daysInYearMonth()返回的是您要求的月份之前的天數。在日期中使用日期0時,表示該日期前一個月的最後一天。這就是爲什麼你得到7月30,而不是31。因此,要獲得當月的最後一天,您需要使用下個月。

daysInYearMonth(y,m){ 
    return new Date(y, m+1, 0).getDate() 
} 

接下來的問題是,數組的鍵在0開始,但在幾個月天1開始。所以當你做Array(this.daysInYearMonth(this.year, this.month)).keys()它返回一個從030而不是131的數組。解決這個問題的最簡單方法是編寫一個從1開始的循環,而不是用數組玩遊戲。

let lastday = this.daysInYearMonth(this.year, this.month); 
this.days = []; 
for (let d = 1; d <= lastday; d++) { 
    this.days.push(d); 
}