如何在日期中减去月份

How to subtract months in dates?

本文关键字:日期      更新时间:2023-09-26

我有这个日期函数:

var isAnnual;
var setupDate="05/09/2016"
var currDate = new Date();//today

我需要检查上面日期中个月的减法是否等于零。

你知道实现它的最佳方式是什么吗?

从日期中提取月份并减去

注:月份从0开始,即1月-0日,12月-11日

var s= new Date("05/09/2016");
var currDate = new Date();
console.log(s.getMonth()-currDate.getMonth());

我认为这个问题问得不是很准确,因为它并没有真正描述你想要什么,例如,至少有以下选项:

1.)您想将当前月份与给定日期的月份进行比较,顺便说一句,该月份的格式也不准确。伪代码:

givenDate := "05/09/2016";
currentDate := determineCurrentDate();
givenMonth := extractMonthFromDateString(givenDate);
currentMonth := extractMonthFromDate(currentDate);
return givenMonth = currentMonth;

2.)您想确定currentDate是否在给定日期的月份内伪代码:

givenDate := "05/09/2016";
currentDate := determineCurrentDate();
givenMonth := extractMonthFromDateString(givenDate);
currentMonth := extractMonthFromDate(currentDate);
givenYear := extractYearFromDateString(givenDate);
currentYear := extractYearFromDate(currentDate);
return givenMonth = currentMonth AND givenYear = currentYear;

第一种方法的基于JS的解决方案如下,第二种方法很容易构建:

var setupDate = "05/09/2016"; // Format: dd/mm/yyyy
var currDate = new Date();
var monthsEqual = currDate.getMonth() == setupDate.replace(
        /('d'd)'/('d'd)'/('d{4})/, // regex for dd/mm/yyyy
        function(date, day, month, year){ // regard the order of the params
            return new Date(year, parseInt(month)-1, parseInt(day)).getMonth();
        });

console.log(monthsEqual);