Javascript setMonth 显示不正确的日期

标签 javascript date

如果我的日期是 2014 年 5 月 31 日,那么如果我说 date.setMonth(date.getMonth() + 1) 到下个月,我得到 2014 年 7 月 1 日。我希望得到 6 月2014 年 30 日。我猜这是因为 6 月没有 31 天,所以 JavaScript 尽量避免错误。

我编写了一个特殊的函数,根据计算实际对该日期对象执行 setDate、setMonth 和 setYear 函数。似乎单独使用 setMonth 并没有做正确的事情。

想法,

大卫

最佳答案

您是否要从现在起 1 个月?如果是这样,你得到的是正确的。从 5 月 31 日开始的 1 个月是 7 月 1 日,而不是 6 月 30 日。如果您希望它仅根据本月的天数移动到第二个月:

例如:2014 年 1 月 31 日 -> 2014 年 2 月 28 日 或者你提到的情况,你可以使用一个小技巧来使用当前天数的最小值和下个月的天数来让你在同一个月:

// Assume its yesterday
var date = new Date(2014, 4, 31);
// Get the current date
var currentDate = date.getDate();
// Set to day 1 to avoid forward
date.setDate(1);
// Increase month by 1
date.setMonth(date.getMonth() + 1);
// Get max # of days in this new month
var daysInMonth = new Date(date.getYear(), date.getMonth()+1, 0).getDate();
// Set the date to the minimum of current date of days in month
date.setDate(Math.min(currentDate, daysInMonth));

关于Javascript setMonth 显示不正确的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23976513/

相关文章:

javascript - 以一个括号开头的 IIFE 不起作用

javascript - 围绕纯数字变量值的引号

javascript - 新日期返回无效日期 safari

ruby-on-rails - Rails 时间是否被打破为午夜?

javascript - 使 Div 在函数中可见时出错

javascript - 将数组转换为 JSON 数组

javascript - javascript中的Date.UTC()方法是否创建本地时区或GMT

iphone - 如何在 iPhone 中获取两天之间的差异

javascript - Mongoose 保存与插入与创建

JavaScript:Date 的 toString() 和 toLocaleString() 方法之间的区别