Title: Find the days, hours, minutes, or seconds between two dates in C#
This example uses a TimeSpan to find the days, hours, minutes, or seconds between two dates.
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();
TimeSpan elapsed = DateTime.Now - date;
txtDays.Text = elapsed.TotalDays.ToString();
txtHours.Text = elapsed.TotalHours.ToString();
txtMinutes.Text = elapsed.TotalMinutes.ToString();
txtSeconds.Text = elapsed.TotalSeconds.ToString();
}
else
{
txtParsed.Clear();
txtDays.Clear();
txtHours.Clear();
txtMinutes.Clear();
txtSeconds.Clear();
}
}
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.
Download the example to experiment with it and to see additional details.
|