Reputation: 2420
In a senario I need to find out the difference between two dates.For example Start date is 01/01/2012 and To Date is 01/10/2013 .I need to get the output as 1.9 years.
int tDays=(ToDate.Subtract(FromDAte).Days+1);
int years = tDays / 365;
int months = (tDays % 365) / 31;
But this calculation is wrong in case of Leap years.
Upvotes: 1
Views: 1358
Reputation: 317
Try this!
DateTime date_start = new DateTime(2011, 1, 30);
DateTime date_end = new DateTime(2012, 2, 29);//leap year
DateTime tmp_dtStart = date_start;
DateTime tmp_dtEnd = date_end;
//FIX FOR LEAP YEAR
//If the day is the last day of the month just adding 1 day. This might solve the leap year problem.
if (tmp_dtStart.Day == DateTime.DaysInMonth(tmp_dtStart.Year, tmp_dtStart.Month))
{
tmp_dtStart= tmp_dtStart.AddDays(1);
}
if (tmp_dtEnd.Day == DateTime.DaysInMonth(tmp_dtEnd.Year, tmp_dtEnd.Month))
{
tmp_dtEnd= tmp_dtEnd.AddDays(1);
}
DateTime diff = new DateTime((tmp_dtEnd - tmp_dtStart).Ticks);
int years = diff.Year - 1;
int month = diff.Month - 1;
string outStr = string.Format("{0}.{1} years", years, month);
I have edited previous code to handle the leap year.
Logic is, (i have used 2 temp date variable without touching the actual date variable) Checking for the day whether it is equals to last day of the month . If yes then add 1 to day and it moves to next month.
I have tested few of the dates it is working fine.
Upvotes: 0
Reputation: 706
If all you need is simply a value, you can use Ticks
property. For example:
//Calculate Ticks in one year
var now = DateTime.Now;
var ticksInYear = (now.AddYears(1) - now).Ticks;
//Create some dates
DateTime first = DateTime.Today.AddYears(-1);
DateTime second = Datetime.Today;
//Get the difference
long value = (second.Ticks - first.Ticks)/ticksInYear;
Upvotes: -1
Reputation: 61
You should create a DateTime Object with your regarding dates. Then you can create the difference between two DateTimes, the result is a TimeSpan object.
Upvotes: 0
Reputation: 1504172
My Noda Time library is built for exactly this sort of thing:
LocalDate start = new LocalDate(...);
LocalDate end = new LocalDate(...);
Period period = Period.Between(start, end);
Console.WriteLine("{0} years, {1} months, {2} days",
period.Years, period.Months, period.Days);
Note that this will also deal with the fact that months aren't always the same length - so for example, February 1st to March 1st 2013 (28 days) == 1 month, whereas March 1st to March 29th (also 28 days) == 0 months, 28 days.
That will get you months, years and days - I'm not sure where you get "1.9" from based on your example, unless you're using "years.months", which I'd strongly recommend against as it looks like you mean "very nearly 2 years".
Upvotes: 8