javascript - 如何在 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 或任何数字)来计算新日期。
解决方案
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; }
推荐阅读
- spring - 如何创建 URL slug 扩展?
- render - 如何渲染动态模板?
- apache - SOLR 8.1.1 SynonymQuery(parsedQuery 中的同义词
- clearcase - 我如何从不是 ClearCase 中最新祖先的祖先中签出?
- scala - 创建新的 StreamingContext 时出现 AbstractMethodError
- java - 从 Java 列表中删除记录
- javascript - VueJS
- 引发不匹配的 HTML - 警告?
- vb.net - 如何使用 ScrollBars 打印 Container 的隐藏和可见内容
- ios - 尝试在 MKAnnotation 中按下信息按钮时播放声音
- apache-spark - Spark DataFrame如何在mapPartitions之后保留排序和分区信息