The only thing available out-of-the-box in C# is using TimeSpan. Unfortuanately the only calculations TimeSpan can return is the number of days, hours, minutes, seconds and milliseconds. But how about the years, months and days than?
Here's a simple method to show the possibilities of the TimeSpan:
public void PrintDateDiffUsingTimeSpan(DateTime begin, DateTime end) { TimeSpan span = end - begin; StringBuilder str = new StringBuilder(); str.Append("Total span: "); str.Append(span.Days + " days, "); str.Append(span.Hours + " hours, "); str.Append(span.Minutes + " minutes, "); str.Append(span.Seconds + " seconds, "); str.Append(span.Milliseconds + " milliseconds"); Console.WriteLine(str.ToString() + "\n"); Console.WriteLine("Total Days: " + span.TotalDays); Console.WriteLine("Total Hours: " + span.TotalHours); Console.WriteLine("Total Minutes: " + span.TotalMinutes); Console.WriteLine("Total Seconds: " + span.TotalSeconds); Console.WriteLine("Total Milliseconds: " + span.TotalMilliseconds); }
I ended up using a freely available .NET library called 'Time Period'. The source code can be found here. There's also an on line demo and documentation available.
Here's a simple method to show some the possibilities of the TimeSpan:
public void PrintDateDiff(DateTime begin, DateTime end)
{
DateDiff diff = new DateDiff(begin, end);
StringBuilder str = new StringBuilder();
str.Append("Total difference: ");
str.Append(diff.ElapsedYears + " years, ");
str.Append(diff.ElapsedMonths + " months, ");
str.Append(diff.ElapsedDays + " days");
Console.WriteLine(str.ToString() + "\n");
Console.WriteLine("Total Days: " + diff.Days);
Console.WriteLine("Total Weeks: " + diff.Weeks);
Console.WriteLine("Total Weekdays: " + diff.Weekdays);
Console.WriteLine("Total Quarters: " + diff.Quarters);
Console.WriteLine("Total Hours: " + diff.Hours);
}
There are much more possibilities in the DateDiff class of the Time Period library. There are even much more classes available in the library. To know more of the capabilities of this library I again refer to the documentation.
Source: http://www.itenso.com/en/
simply do like this
BeantwoordenVerwijderenString diff2 = (secondDate - firstDate).TotalDays.ToString();
http://csharp.net-informations.com/statements/csharp-date-difference.htm
ling
Actually, this would only return the difference in days... I needed the years, months, etc. seperately.
Verwijderen