Horius
Horius

Reputation: 129

Calculating an elapsed Time

I want to calculate the elapsed time which a process needs to execute based on 2 strings with timestamps in the format HH:mm:ss:ff. Therefore I splitted those strings, turned them into an integer and subtracted them.

What I tried is to subtract the last timestamp from the first. It also works sometimes. But I also get a lot of weird feedback out of this - for example: 0:0:-3:-18 I think this is the result of not handling the case if a value is higher than another and they get divided.

Here is the function I use to subtract the strings:

        static string calculateElapsedTime(string startTime, string endTime)
    {
        try
        {
            string[] startTimeSplit = startZeit.Split(new char[] { ':', '.' });
            string[] endTimeSplit = endZeit.Split(new char[] { ':', '.' });
            int[] elapsedTime = new int[4];

            endTimeSplit[0] = Convert.ToInt32(endTimeSplit[0]) - Convert.ToInt32(startTimeSplit[0]);
            endTimeSplit[1] = Convert.ToInt32(endTimeSplit[1]) - Convert.ToInt32(startTimeSplit[1]);
            endTimeSplit[2] = Convert.ToInt32(endTimeSplit[2]) - Convert.ToInt32(startTimeSplit[2]);
            endTimeSplit[3] = Convert.ToInt32(endTimeSplit[3]) - Convert.ToInt32(startTimeSplit[3]);

            string elapsedTimeString = string.Format("{0}:{1}:{2}:{3}", endTimeSplit[0], endTimeSplit[1], endTimeSplit[2], endTimeSplit[3]);

            return elapsedTimeString;
        }
        catch( Exception ex )
        {
            Console.WriteLine(ex.Message);
            return "null";
        }
    }

And I got the value for the parameters by simply getting the time like:

DateTime.Now.ToString("HH:mm:ss:ff", System.Globalization.DateTimeFormatInfo.InvariantInfo);

SOLUTION:

There is a Function called Stopwatch in the Namespace System.Diagnostics.

You can use it as following:

Stopwatch watch = new Stopwatch();
watch.Start();
//Prozess
watch.Stop();
Console.WriteLine(watch.Elapsed);

Upvotes: 3

Views: 7262

Answers (2)

Rikudou En Sof
Rikudou En Sof

Reputation: 758

I came across this, and this is what I created. You can add the month's calculation if you wish. You can also use the total<days, hours...>, but it will defeat the code. Generate a converter to convert to DateTime. It helps a lot.

public static string TimeElapsed(DateTime start_Time, DateTime end_time)
{
  string result = "";
  var subtractedDate = end_time.Subtract(start_Time);
  if (subtractedDate.Days >= 7)
  {
    var weeks = (int)(subtractedDate.Days / 7);
    if (weeks >= 52)
    {
      var years = (int)(weeks / 52);
      result = $"{years} years ago";
    }
    else
    {
      result = $"{weeks} weeks ago";
    }
   
  }
  else if (subtractedDate.Days > 0 && subtractedDate.Days < 7)
  {
    result = $"{subtractedDate.Days} days ago";
  }
  else
  {
    if (subtractedDate.Hours> 0)
    {
      result = $"{subtractedDate.Hours} hours ago";
    }
    else
    {
      if (subtractedDate.Minutes > 0)
      {
        result = $"{subtractedDate.Minutes} mins ago";
      }
      else
      {
        result = "< 1 min ago";

      }
    }
  }

  return result;
}

Upvotes: 2

Felipe Oriani
Felipe Oriani

Reputation: 38638

You could convert to TimeSpan with the correct format and subtract them, for sample:

string format = "HH:mm:ss:ffff";
TimeSpan startTimeSpan = TimeSpan.ParseExact(startTime, format, null);
TimeSpan endTimeSpan = TimeSpan.ParseExact(endTime, format, null);

TimeSpan result = startTimeSpan - endTimeSpan;

string elapsedTimeString = string.Format("{0}:{1}:{2}:{3}", 
                                          result.Hours.ToString("00"), 
                                          result.Minutes.ToString("00"),
                                          result.Seconds.ToString("00"),
                                          result.Milliseconds.ToString("00"));

return elapsedTimeString;

Take a look at the TimeSpan Formats at MSDN documentation.

Upvotes: 6

Related Questions