0

I'd like to display a TimeSpan value, formatted as mm:ss (minutes, seconds).

The code currently performs this like this:

var timeSpan = GetTimeUntilNextEvent();
var str = DateTime.MinValue.Add(timeSpan).ToString(@"mm\:ss");

I wonder whether that is correct code. I saw other samples that show this technique, but I am not really sure what is the reason for adding something to the MinValue of DateTime.

Why cannot this code be used ? It seems to product a valid result.

var str = DateTime.FromBinary(0).Add(timeSpan).ToString(@"mm\:ss");
lysergic-acid
  • 19,570
  • 21
  • 109
  • 218
  • 2
    What `GetTimeUntilNextEvent` method do? What do you try to achieve exactly? – Soner Gönül Feb 25 '15 at 09:22
  • `DateTime.Add` returns `DateTime`, so this question is not about a formatted `TimeSpan` but `DateTime`. For thast reason you don't need `.ToString(@"mm\:ss")` but you can use `.ToString("mm:ss")`. – Tim Schmelter Feb 25 '15 at 09:23
  • `DateTime.MinValue` and `DateTime.FromBinary(0)` are exactly the same. – DavidG Feb 25 '15 at 09:25
  • Well, technically adding a negative timespan to MinValue causes an exception, which is exactly what i'm trying to prevent. – lysergic-acid Feb 25 '15 at 09:28
  • You want to prevent a negative time span? – DavidG Feb 25 '15 at 09:29
  • I just realized that it's exactly the same thing, and i probably really should just normalize to start at 0.... – lysergic-acid Feb 25 '15 at 09:30
  • possible duplicate of [How can I String.Format a TimeSpan object with a custom format in .NET?](http://stackoverflow.com/questions/574881/how-can-i-string-format-a-timespan-object-with-a-custom-format-in-net) – DrKoch Feb 25 '15 at 09:31

1 Answers1

0

You don't need DateTime to format a TimeSpan. You could simply use the timespan ToString() method:

TimeSpan timeSpan = new TimeSpan(5, 12, 2);
String str = timeSpan.ToString(@"mm\:ss"));

Also see Link.

Gaander
  • 81
  • 1
  • 8