javascriptdatedayofmonth

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


Does anyone know how to always set a date to 28th day of current month, or 28th day of the next month if date has passed 28th day of current month, and then calculate new date using variable (number of months). This is how it was done in .NET:

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

What I tried so far:

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>");

I already have a problem with setting next month if day is 29, 30 or 31. Then I need to count new date by adding months (5, 7 or 15 or just any number).


Solution

  • Here is code, that works for me! Thankseveryone for helping me out!

    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);