我正在嘗試構建一個自定義日期選擇器。我在對 JS Date 的理解上苦苦掙扎,但是我需要幫助來確定差距。嘗試使用 for 回圈創建日期時發生了一些奇怪的事情!
基本上我創建一個日期,獲取該月的天數,并Date使用有效的日期字串創建物件,以便使用該數字進行顯示/處理。
幾個月(根據我的測驗,月份 # > 9),第 9 天重復,所以整數10不會進入日期。日期的其余部分在 1 后面創建。
代碼:
export const MinimalDatepicker = () => {
// grab an arbitrary date for further use
const today = new Date('2022-11-01');
console.log('Month:', today.getMonth() 1);
const daysInCurrentMonth = getDaysInMonth(today);
const daysToShow: Date[] = [];
Array.from(Array(daysInCurrentMonth).keys()).map((day) => {
const date = new Date(`${today.getFullYear()}-${today.getMonth() 1}-${day 1}`);
daysToShow.push(date);
});
console.log(daysToShow.map((d) => d.getDate()))
return (
<div>stuff</div>
);
};
月份 # > 9 的輸出日志 - 注意重復9- 最后一天應該是 31,而不是 30:
Month: 10
[1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
如果我們將月份回滾到 10,我們會看到問題不再發生:
Month: 9
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
更多的困惑
I understand that in JS Date, month index starts at zero, so I use date.getMonth() 1 to "accurately" represent my current month, but I'm not sure how accurate it is.
In my date string example of 2022-11-01, when I call .getMonth(), I actually receive a date that is 2 integers behind the number used in the string; in the logs above, 2022-11-01 yields a month of 9 1 in the logs, such that 2022-01-01 actually yields a December date.
uj5u.com熱心網友回復:
我相信您面臨的問題是日期字串格式錯誤的結果(或者至少很可能是這樣)。getMonth和day都是數字,這意味著當它們小于 10 時,它們將是單個字串。2022-1-1不是 JS 決議的有效日期。padStart可以幫助正確格式化。
嘗試:
const date = new Date(`${today.getFullYear()}-${String(today.getMonth() 1).padStart(2, "0")}-${String(day 1).padStart(2, "0")}`);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/453947.html
