C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
DateTime.ParseNow: 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.
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"));
}
}
Output
3-03-2008 was 247 days ago
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.
ToStringDateTime Format