C# DateTime, Elapsed

TimeSpan

Time has elapsed since a certain date. With DateTime and TimeSpan we can compute this elapsed time period. We can display the age of someone or how many days ago a site was updated. We provide an example elapsed time method.

DateTimeTimeSpan

Example

The .NET Framework provides methods that are useful for this, but the syntax is sometimes hard. What we must do is initialize two DateTime structs and then subtract one from the other. The example then shows how to get the TimeSpan.

DateTime Subtract
Program that calculates elapsed time: C#

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"));
    }
}

Output

3-03-2008 was 247 days ago
Note

DateTime.Parse. This is not strictly part of the solution, but we must have a DateTime from some time in the past. In the example, we create the DateTime of March 3 in the year 2008.

DateTime.Parse String Method

DateTime.Now. This is how we can get the current day and time. DateTime.Now is extremely useful in many parts of .NET. Look at how we take the DateTime.Now and call Subtract on it, passing it the earlier date.

Squares

TimeSpan is used with TotalDays. Subtract returned a TimeSpan. We must use the TotalDays property now to get the entire length in days in the time span. The Days property will only return the component of the time, not the total days.

Note:We call daysAgo.ToString("0") on the double returned by TotalDays. This value has a decimal—we don't need this for display.

So:We display "145 days" instead of "144.9983" days. This makes for a better user interface.

ToString MethodDateTime Format

Summary

We computed elapsed days in the C# language. You can view more DateTime articles at this site for more useful methods. Use the code here for an accurate method of getting the time elapsed.


C#: Time