首页 > 解决方案 > 如何在 JavaScript 中计算日期,以获得月份中的同一天 + 某个月份(变量)

问题描述

有谁知道如何始终将日期设置为当月的第 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 或任何数字)来计算新日期。

标签: javascriptdatedayofmonth

解决方案


toLocaleDateString()您可以使用javascriptDate对象 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; }


推荐阅读