المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : how to get difference between 2 dates in years:months format?



C# Programming
08-31-2012, 02:30 PM
Hi all,
AM working on a C# project..
my requirement is as follows:
there are 2 dates viz date1 & date2.
if date1 > date2
the difference should come as e.g (3years,2months)
if date1 < date2
the difference should come as e.g (-3years,-2months)
I am able to get the first scenario but the second scenario I am having problems with, not able to calculate the number of months in negative quite correctly...
Below is the code used in case of positive scenario,currentdate is alwys greater than the assetCapDate passed as a value:

public string newmethod(string assetCapDate)
{

string timeStr = string.Empty;
int years = 0;
int months = 0;
int days = 0;
TimeSpan ts = new TimeSpan();
System.DateTime date1 = DateTime.Now;
System.DateTime date2 = Convert.ToDateTime(assetCapDate);
ts = date1.Subtract(date2);
years = (ts.Days/365);
do
{
for(int i=0; i =0)
{
months = i;
}
else
{
break;
}
}

if(months > 12)
years = years + 1;
}while(months > 12);

days = date1.Subtract(date2.AddYears(years).AddMonths(months)).Days;

if (years > 0)
{
timeStr += years.ToString() + " Years, ";
}
if (months > 0)
{
timeStr += months.ToString() + " Months";
}

if (days > 0)
{
timeStr += days.ToString() + " Days";
}

return(timeStr);
}

Any help would be highly appreciated.

I am not sure whether this question falls under C# domain..Moderators please advise accordingly..will move this question to another domain if required.
Regards
Anurag