Thursday, August 6, 2009

Difference between two dates as x month and y days.

If you have to find the difference between two dates as x month and y days .

Let the two dates be "StartDate" and "EndDate" and x be the month and y be the days after taking difference between StartDate and EndDate.
int x,y;
x= MonthDifference(StartDate,EndDate);

where MonthDifference(startDate,EndDate) is a function :

public int MonthDifference(DateTime startDate, DateTime endDate)
{
int noOfYears = endDate.Year - startDate.Year;
int noOfMonths = (endDate.Month - startDate.Month);
noOfMonths = noOfMonths + (noOfYears * 12);
return noOfMonths;
}


//To calculate No of Days and Month ..


if (System.DateTime.DaysInMonth(EndDate.Year, EndDate.Month)== (EndDate.Day - StartDate.Day + 1))

{
x = x+ 1;
y = 0;
}
else
{
if(EndDate.Day < StartDate.Day)
{
y = System.DateTime.DaysInMonth(user.EndDate.AddMonths(-1).Year,
user.EndDate.AddMonths(-1).Month) -
StartDate.Day + EndDate.Day + 1;
x = x - 1;
}
else
{
y= EndDate.Day -StartDate.Day + 1;
}
}


In this way you can get the difference between two dates as x month and y days.

Thanks
Varun

Monday, August 3, 2009

Default parameters in c# 4

I just read about a very cool feature of "default parameter" in a webblog of a microsoft employee.I just want that others should also be aware of this feature so,I am included this in my post also.

Presently in c# 3.5 we all are just using the function overloading in order to provide the default or optional parameter functionality.e.g

public class oldclass
{
public string A{ get; set; }
public string B{ get; set; }
public string C{ get; set; }

public oldclass(string a)
{
A= a;
B= "B";
C= string.Empty;
}
public oldclass(string a, string b)
{
A= a;
B= b;
C= string.Empty;

}
public oldclass(string a, string b, string c)
{
A= a;
B= b;
C= c;
}
}
But now in c# 4 what we do is:-
public class newclass
{
public string A{ get; set; }
public string B{ get; set; }
public string C{ get; set; }

public newclass(string a, string b="B", string c=string.Empty)
{
A= a;
B= b;
C= c;
}
}
if we initialize constructor using-> new newclass("A");
then values for A="A",B="B"and C="".

So,Its quite cool to include this feature in c# 4 so that now,we don't have to use function overloading for getting functionality of optional parameters.