gremo
gremo

Reputation: 48909

How can I calculate remaining time in hh:mm:ss knowing total steps, current step and duration (milliseconds)?

Question as title, this is not working, can't understand why:

  // Get total steps, current step and duration in milliseconds
  int current = stats[0]; int total = stats[1]; int duration = stats[2];

  // Calculate the time span (of remaining time)
  var remaining = TimeSpan.FromMilliseconds((total - current) * duration);

  // Update the label
  label.Text = string.Format("Tempo rimanente: {0}",
    (new DateTime(remaining.Ticks)).ToString("hh:mm:ss"));

Upvotes: 1

Views: 3555

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500855

Why are you trying to convert a TimeSpan to a DateTime at all? "Remaining time" is a concept which is ideally suited to a TimeSpan, not a DateTime. You might want to convert it to the "estimated completion time" which would be a DateTime, but otherwise just use the TimeSpan.

Note that in .NET 4, TimeSpan gained custom format abilities, if you really need them - but I suspect the default format is likely to be okay for you, at least to start with.

Upvotes: 1

Try changing

(new DateTime(remaining.Ticks)).ToString("hh:mm:ss"));

To

remaining.Hours + ":" + remaining.Minutes + ":" + remaining.Seconds);

OR even:

 // Update the label
 label.Text = string.Format("Tempo rimanente: {0:00}:{1:00}:{2:00}",
    remaining.Hours, remaining.Minutes, remaining.Seconds)

Upvotes: 1

Related Questions