Stefan Ciprian Hotoleanu
Stefan Ciprian Hotoleanu

Reputation: 2292

Are there any JavaScript methods that can replicate the Oracle's ADD_MONTH() functionality

1) Oracle's example of ADD_MONTHS(date, 1):

SELECT ADD_MONTHS('30-Nov-15', 3) FROM dual;

February, 29 2016 00:00:00

2) JavaScript:

var date= new Date("Mon Nov 30 2015 00:00:00"); 
date.setMonth(date.getMonth() + 3);

Tue Mar 01 2016 00:00:00

Are there any JavaScript methods that can replicate the Oracle's ADD_MONTH() functionality ?

Upvotes: 1

Views: 116

Answers (2)

Marmite Bomber
Marmite Bomber

Reputation: 21063

If you want to implement the same logik as in Oracle function - i.e. for "shorter" month you do not overflow in the next month, I guess you will need to do it yourself:

Pseudocode:

 myDay = date.getDate(); // save the date
 date.setMonth(date.getMonth() + 3);  // add months
 myNewDay = date.getDate();
 while  (myDay !=  myNewDay & myNewDay <= 3) {
    myNewDay = myNewDay -1 // go back one day
    date.setDate(myNewDay); // restore the
 }

So if you end with the same day of the month after adding months you are ready. If you get a different day of month, it will be 1,2 or 3 (the difference in month length); go back day by day until you reach the end of the month.

This is my knowledge of the Oracle algorithm. HTH.

Upvotes: 2

kameron tanseli
kameron tanseli

Reputation: 109

date.getMonth() 

returns the previous months date instead of this months date. So to add to the correct date just do

date.setMonth(date.getMonth() + 2);

Upvotes: 1

Related Questions