How many days ago was a certain date? Find the time elapsed in days since a certain date, such as a birthdate or other important date. You may want to display the age of someone or how many days ago your site was updated.
The .NET framework provides several methods that are useful for this, but the syntax is sometimes hard. What we must do is initialize two DateTime objects and then subtract one from the other. Then we use TimeSpan.
using System;
class Program
{
static void Main()
{
//
// Initialize a date in the past.
// This is March 3, 2008.
//
string someDate = "03-03-2008";
//
// 1.
// Parse the date and put in DateTime object.
//
DateTime startDate = DateTime.Parse(someDate);
//
// 2.
// Get the current DateTime.
//
DateTime now = DateTime.Now;
//
// 3.
// Get the TimeSpan of the difference.
//
TimeSpan elapsed = now.Subtract(startDate);
//
// 4.
// Get number of days ago.
//
double daysAgo = elapsed.TotalDays;
Console.WriteLine("{0} was {1} days ago",
someDate,
daysAgo.ToString("0"));
//
// "03-03-2008 was 247 days ago"
//
}
}Look at how we call daysAgo.ToString("0") on double returned by TotalDays. We do this because TotalDays has a decimal, which we don't care about for the display. We want to display "145 days" instead of "144.9983" days.
View more DateTime articles at this site for more useful methods. Use the code here for an accurate method of getting the time elapsed. DateTime in C# is simple, but we just need to know the right methods. [C# - DateTime Use]