Javascript 日期对象关闭一个月

发布于 2025-01-10 20:56:48 字数 583 浏览 0 评论 0原文

我知道 javascript 从 0 开始计算月份。但是,我不知道在将来获取日期时如何考虑这一点。

例如,当尝试获取明天的日期时,以下代码将返回除月份之外的所有正确内容(打印为下个月):

const weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const month =  ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

var today = new Date();
today.setUTCDate(today.getUTCDate()+1);

let newDate = weekday[today.getDay()] +' '+today.getDate()+' '+month[today.getDay()]+', '+ today.getFullYear();

console.log(newDate)

I understand that javascript counts the months starting from 0. However, I don't know how to account for this when getting a date in the future.

For example, when attempting to get the date for tomorrow, the following code returns everything correct except for the month (prints as next month):

const weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const month =  ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

var today = new Date();
today.setUTCDate(today.getUTCDate()+1);

let newDate = weekday[today.getDay()] +' '+today.getDate()+' '+month[today.getDay()]+', '+ today.getFullYear();

console.log(newDate)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乙白 2025-01-17 20:56:49

只需将 today.getDay() 替换为 today.getMonth()

const weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const month =  ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

var today = new Date();
today.setUTCDate(today.getUTCDate()+1);

let newDate = weekday[today.getDay()] +' '+today.getDate()+' '+month[today.getMonth()]+', '+ today.getFullYear();

console.log(newDate)

Just replace today.getDay() to today.getMonth()

const weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const month =  ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

var today = new Date();
today.setUTCDate(today.getUTCDate()+1);

let newDate = weekday[today.getDay()] +' '+today.getDate()+' '+month[today.getMonth()]+', '+ today.getFullYear();

console.log(newDate)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文