簡體   English   中英

非閏月 2 月份的 JS 問題

[英]JS problem with the month of February in non-leap months

我正在實施一個簡單的日歷,但我對所有非閏熱月份都有問題。

如果您單擊下一步直到 2023 年 2 月,則顯示三月,如果您前進到 2024 年(這是一個飛躍),一切正常,我該如何解決?

 let nav = 0; let test = () => { const dt = new Date(); dt.setMonth(new Date().getMonth() + nav); const day = dt.getDate(); const month = dt.getMonth(); const year = dt.getFullYear(); const monthName = `${dt.toLocaleDateString("en", { month: "long" })} ${year}`; document.getElementById('feedBack').innerHTML = 'Nav: ' + nav + ' - Day: ' + 1 + ' - Month: ' + month + ' ( <b>' + monthName + '</b> ) - Year: ' + year; } test();
 #feedBack {margin-top:10px}
 <button onclick="nav--;test()">Prev</button> <button onclick="nav=0;test();">Current</button> <button onclick="nav++;test();">Next</button> <div id="feedBack"></div>

等兩天問題就解決了嘿嘿(今天是29/06,你在迭代,29/07、29/08等等)。

或者您可以在增加月份之前更改月份對象。

 let nav = 0; let test = () => { const dt = new Date(); dt.setDate(1); // this will move to the first day of the current month dt.setMonth(new Date().getMonth() + nav); const month = dt.getMonth(); const year = dt.getFullYear(); const monthName = `${dt.toLocaleDateString("en", { month: "long" })} ${year}`; document.getElementById('feedBack').innerHTML = 'Nav: ' + nav + ' - Day: ' + 1 + ' - Month: ' + month + ' ( <b>' + monthName + '</b> ) - Year: ' + year; } test();
 #feedBack {margin-top:10px}
 <button onclick="nav--;test()">Prev</button> <button onclick="nav=0;test();">Current</button> <button onclick="nav++;test();">Next</button> <div id="feedBack"></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM