繁体   English   中英

我如何计算 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()和 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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM