Increase decrease date by day or month or year using javascript

Requirement:-

Increase / decrease date by day or month or year using javascript.
In this article I will take example of months to increase or decrease. In same way we can do for day or year.

Solution:-

To increase or decrease date; we require below inputs:
Current Date, monthcount to increase, Boolean value to Add or subtract.
Once you have these call use below functions which will return expected date object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function MainFunction()
{
        var fromDateString = "12/01/2011";
        var monthCount = 4;
	// True means it will add months
	// False means it will subtract months
        var isAdd = true; 
 
	var newDate = GetNewDate(fromDateString, monthCount, isAdd);
 
        var newYear = newDate.getFullYear();
        var newMonth = newDate.getMonth() + 1; // Note: getMonth 00 for Jan and 11 for Dec
	var newDay = newDate.getDay();
 
 
}    
// Add or Subtract given count from given date
function GetNewDate(dateString, monCount, isAdd) {
 
	//uncomment below line if you need result this way: Jan-March difference is 3
        // monCount = monCount - 1; 
        var d = dateObj;
        if (isAdd) {
            d.setMonth(d.getMonth() + monCount);
        }
        else {
            d.setMonth(d.getMonth() - monCount);
        }
        return d;
    }

Thanks!
Avinash

calendarMay 18, 2012 В· cardInfoyen В· commentsNo Comments
tagTags: ,  В· Posted in: JavaScript

Leave a Reply

Spam Protection: , required

myworldmaps infoyen