C# Get Day Count Elapsed From DateTimeCompute the difference between two DateTimes. Count elapsed days.
DateTime, elapsed. 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.
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
Here We get a DateTime from some time in the past. In the example, we create the DateTime of March 3 in the year 2008.
Now This is how we can get the current day and time. Look at how we take the DateTime.Now and call Subtract on it, passing it the earlier date.
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.
DateTime Format
C# program that calculates elapsed time
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")); } }
3-03-2008 was 247 days ago
Summary. We computed the count of elapsed days. 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.
© 2007-2022 sam allen.
see site info on the changelog.