Friday, February 10, 2012

C# using the TimeSpan structure to calculate remaining time

If you want to calculate the time left from now to some future date, this is what I used in my Reminder Winform/C# application:


The function gets DateTime parameter with a future date:


void remained_time(DateTime date_time_reminder)
{
    DateTime date_time_now = DateTime.Now;
    TimeSpan time_span = date_time_reminder - date_time_now;

    string time = string.Format("{0:00}:{1:00}:{2:00}", time_span.Hours, time_span.Minutes, time_span.Seconds);
    tb_time.Text = "Left: " + time_span.Days.ToString() + " days, " + time;
}


The output is: Left: 42 days, 21:13:07

Note:
It's better to use string.Format in a way stated above because the plain TimeSpan.Hours/Minutes/Seconds displays only one digit when the TimeSpan value is a single digit, i.e. 12:3:3 instead of 12:03:03

No comments:

Post a Comment