neolancer
neolancer

Reputation: 11

Calculating average time using TimeSpans in C#

I am trying to calculate an average time by subtracting end time by start time then dividing the difference by a count. In my case the count is products scanned. I want to output the result in a string using this format "HH:mm:ss". I have been playing around with my code but I can't get it to work.

Here are my variables:

    private DateTime woStartTime;
    private DateTime woEndTime;
    private TimeSpan difference;
    private long average;

Here is the value for Start Time

    woStartTime = DateTime.Now;

Here is my method for calculating average time

 public void Calculate_Average_Time()
    {
        try
        {
            woEndTime = DateTime.Now;
            difference = woEndTime - woStartTime;
            long dTime = Convert.ToInt64(difference.Ticks);
            average = dTime / Scanned;
            DateTime aTimeS = Convert.ToDateTime((average / 86400M).ToString("HH:mm:ss", CultureInfo.InvariantCulture));
            lblError.Text = aTimeS.ToString(); // display to verify results
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

I keep getting an exception error: string was not recognized as a valid DateTime. There is an unknown word starting at index 0.

What am I doing wrong? Please help.

Upvotes: 1

Views: 2009

Answers (2)

MariusUt
MariusUt

Reputation: 752

You shouldn't use DateTime at all. Use System.Diagnostics.Stopwatch instead when you want to accurately measure elapsed time.

I'll answer your question in terms of DateTime anyway, hoping that'll be helpful for you in the future :) You don't need to first convert to string, then convert to DateTime. Use

TimeSpan aTimeS = new TimeSpan(average);

This will create a new TimeSpan with the specified number of ticks. Note the usage of TimeSpan rather than DateTime.TimeSpan represents an amount of time, while DateTime is a specific point in time.

Upvotes: 4

Praveen Paulose
Praveen Paulose

Reputation: 5771

Using DateTime is not the correct way. You have ticks as the average which may not correspond to a DateTime. Use TimeSpan instead as shown below:

        try
        {
            woEndTime = DateTime.Now;
            difference = woEndTime - woStartTime;
            long dTime = Convert.ToInt64(difference.Ticks);
            average = dTime / Scanned;
            TimeSpan averageTimeSpan = new TimeSpan(average);                
            lblError.Text = averageTimeSpan.ToString(@"hh\:mm\:ss"); // display to verify results

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

Note: The format for TimeSpan differs from DateTime formats. You need to escape the colons.

Upvotes: 0

Related Questions