BLOG.CSHARPHELPER.COM: Use a TimeSpan to find the number of days, hours, minutes, or seconds between two dates in C#
Use a TimeSpan to find the number of days, hours, minutes, or seconds between two dates in C#
When the user changes the date text, the program executes the following code.
// If the text is a date, display // the elapsed time between then and now. private void txtDate_TextChanged(object sender, EventArgs e) { DateTime date; if (DateTime.TryParse(txtDate.Text, out date)) { txtParsed.Text = date.ToString();
The program uses TryParse to try to parse the text. If the text represents a valid date, the program subtracts that date from the current one to get a TimeSpan. It then displays the elapsed time in total days, hours, minutes, and seconds. For example, if the two dates are 24 hours apart, the text boxes will show 1 day, 24 hours, 1440 minutes, and 86400 seconds.
Note that the TimeSpan structure doesn't have TotalYears, TotalMonths, or TotalWeeks methods because years and months at least don't all have the same lengths. For example, January and February don't have the same number of days.
Comments