我如何计算 JavaScript 中的日期,以获得一个月中的同一天 + 某个月(变量)

How do I calculate the date in JavaScript, to get the same day in month + some month (variable)

有谁知道如何始终将日期设置为当月 28 日,或者如果日期已超过当月 28 日则设置为下个月的 28 日,然后使用变量(月数)计算新日期. 这是在 .NET 中的做法:

DateSerial(Year(DateAdd("m",
AmountOfMonths,
CDate(Invoice_date))),
Month(DateAdd(DateInterval.Month,
AmountOfMonths, CDate(Invoice_date))), 28)

到目前为止我尝试了什么:

var currentDate = new Date();
var day = currentDate.getDate() ;
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
if  (day <= "28") result += day ="28";
else result += day ="28";
if  (day > "28") result = month + "1";
results.html("<b>" + year + "/" + month + "/" + day + "</b>");

如果日期是 29、30 或 31,我在设置下个月时遇到了问题。然后我需要通过添加月份(5、7 或 15 或任何数字)来计算新日期。

您可以尝试使用 toLocaleDateString() and javascript Date 对象 getter 和 setter 方法:

// Returns a string in mm/dd/yyyy format
const GetFormattedDate = d => d.toLocaleDateString('en-US');

const CalculateDate = (dateStr) => {
  var currentDate = dateStr ? new Date(dateStr) : new Date();

  // Log the current actual date
  console.log('Actual date: ', GetFormattedDate(currentDate));

  var day = currentDate.getDate();
  if (day > 28) {
    currentDate.setMonth(currentDate.getMonth() + 1);
  }
  currentDate.setDate(28);

  // Return 28th of current or next month
  return GetFormattedDate(currentDate);
}

// 1 week ago
console.log('Updated date: ', CalculateDate('02/21/2020'))

// Today
console.log('Updated date: ', CalculateDate())

// 1 week later
console.log('Updated date: ', CalculateDate('03/06/2020'))

// 1 month later
console.log('Updated date: ', CalculateDate('03/29/2020'))

// 1 year later
console.log('Updated date: ', CalculateDate('02/21/2021'))
.as-console-wrapper { max-height: 100% !important; top: 0; }

要添加一个月,请将日期中的月份加一。如果日期大于 28,你只需要做一些事情,例如

var currentDate = new Date();
var currentDay = currentDate.getDate() ;
currentDate.setDate(28);

if  (currentDay > 28) {
  currentDate.setMonth(currentDate.getMonth() + 1);
}

var month = currentDate.getMonth() + 1;
var year  = currentDate.getFullYear();

console.log(year + '/' + month + '/' + 28);

这是代码,对我有用!谢谢大家帮助我!

var field = "";
field = record.fields["CreditTime2"];
var currentDate = new Date();
var currentDay = currentDate.getDate() ;
currentDate.setDate(28);
if (currentDay > 28) { currentDate.setMonth(currentDate.getMonth() + 1);
}
//add number of months to already calculated date
currentDate.setMonth(currentDate.getMonth() + parseInt(field));
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
results.html(year + '-' + month + '-' + 28);