【问题标题】:JS Specific ending date calculatorJS 具体结束日期计算器
【发布时间】:2017-07-24 10:08:37
【问题描述】:

如果我的开始日期是 1 月 31 日,然后加上 1 个月,它会返回 3 月 2 日的日期。 我正在尝试制作一个脚本,以这种方式添加几个月的日期:

starting date : 31/01/2000
+1 month = 29/02/2000
+2 months = 31/03/2000
+3 months = 30/04/2000 
....
+12 months = 28/02/2001

另一种情况:

Starting date : 28/02/2001
+1 month : 31/03/2001
+2 months : 30/04/2001
...

所以,如果开始日期是当月的最后一天,那么结束日期必须是当月的最后一天。

所以,我的代码逻辑如下:

var date = new Date(2017,01,30); 1.获取该日期的当前日期。 (X) 2.如果x

我的 JSFiddle 在这里:https://jsfiddle.net/5mfLo8zs/ 我知道语法有什么问题,但它给了我一个 .getDate() is not a function error,可能,这不是唯一的问题。

附:我知道这个主题是重复的,我花了 10 分钟搜索相同的问题,但我找到了如何设置月份的最后一天,但这里我需要更多内容。

【问题讨论】:

  • 试试这个:var endDate = new Date(startDate.getFullYear(), startDate.getMonth() +2, 0)Updated Fiddle

标签: javascript date


【解决方案1】:

你可以试试这样的:

逻辑:

  • 检查过去的日期是否是该月的最后一天?
    1. 如果是,您需要将月数加 1。这是因为,通过将日期创建为下个月的第一天然后减去 1 来获取本月最后一天的逻辑是有效的。
  • 现在初始化一个临时变量,该变量将保存天的值。默认设置为 0。
  • 如果月份相同,则将此临时变量设置为已过的日期。否则设为 0。
  • 现在您拥有创建新日期的所有参数。把它返还。请注意,更新相同的日期变量将覆盖原始值。因此,请尽量避免对其进行任何操作。

function addMonths(date, months) {
  var d = 0;
  var next = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
  if (next.getMonth() === date.getMonth()) {
    d = date.getDate()
  }
  else{
    months++
  }

  // use following line in actual code.
  // return new Date(date.getFullYear(), date.getMonth() + months, d)
  // This line is just fror demonstration purpose.
  return new Date(date.getFullYear(), date.getMonth() + months, d).toDateString();
}

console.log(addMonths(new Date(2017, 0, 31), 1));
console.log(addMonths(new Date(2017, 0, 31), 3));
console.log(addMonths(new Date(2017, 0, 15), 3));
console.log(addMonths(new Date(2016, 11, 31), 1));
console.log(addMonths(new Date(2016, 11, 11), 1));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多