2

Is there a way to convert a given value to elapsed time with a formatting string in .NET? For example, if I have value 4000 and formatting string to be "mm:ss", I should get the elapsed time as 66:40.

Thanks Datte

dattebayo
  • 2,012
  • 4
  • 30
  • 40

2 Answers2

3

You can use the TimeSpan class to make this easier:

var elapsedTime = TimeSpan.FromSeconds(4000);
var formatted = string.Format("{0}:{1}", (int)elapsedTime.TotalMinutes, elapsedTime.Seconds);

Console.WriteLine(formatted);

(You can't use normal format strings for this since you want the total minutes instead of days/hours/minutes/etc.)

porges
  • 30,133
  • 4
  • 83
  • 114
  • So, if I want the formatting string to be anything like "mm:ss", "hh:mm:ss", for each of these, I'll have to calculate the time units manually? Isn't this supported in DateTime or TimeSpan? – dattebayo Oct 04 '11 at 22:10
  • 2
    @dattebayo: The standard format strings only give you the 'leftover' amounts for hh/mm/ss/etc. So if you use "mm\:ss" you'll get "06:40", since the 60 minutes rolls over into 1 hour. You could write your own formatting provider to implement this, but that seems like overkill :) – porges Oct 04 '11 at 22:59
0

Using standard format strings there would be no way to tell which of your format strings are totals and which are component values. For example, should mm produce the total number of minutes, or the minute component? And if it's total, how do we know what the total is? It should be 66.666666 minutes, not 66.

Polynomial
  • 27,674
  • 12
  • 80
  • 107