LuDevGon
LuDevGon

Reputation: 113

Formatting TimeSpan to hours, minutes and seconds

i am trying to find a solution for my issue, i am using TimeSpan to get the total amount of time a window was open by subtracting two Datetime objects. it is working but i am getting milliseconds and i only need hours, minutes and seconds to display. this is the code i am working with _timeStart is initialize outside the method but its just gets the time the window opened.

_timeStop = DateTime.Now;
TimeSpan timeSpent = _timeStop.Subtract(_timeStart);
string.Format($"{timeSpent:hh\\:mm\\:ss}");
_logger.Debug(timeSpent);

Upvotes: 5

Views: 5353

Answers (3)

Fred Smith
Fred Smith

Reputation: 2139

You can use this method:

public static string ConvertTimeSpanToString(TimeSpan ts)
{
  return $"{ts.Days}:{ts.Hours}:{ts.Minutes}:{ts.Seconds}:{ts.Milliseconds}";
}

Or even better:

public static string ConvertTimeSpanToString(TimeSpan ts)
    {

      var days = $"{ts.Days} day{Plural(ts.Days)}";

      var hours = $"{ts.Hours} hour{Plural(ts.Hours)}";

      var minutes = $"{ts.Minutes} minute{Plural(ts.Minutes)}";

      var seconds = $"{ts.Seconds} second{Plural(ts.Seconds)}";

      var milliSeconds = $"{ts.Milliseconds} milliseconde{Plural(ts.Milliseconds)}";

      return $"{days} {hours}:{minutes}:{seconds}:{milliSeconds}";
    }

    private static string Plural(int number)
    {
      return number > 1 ? "s" : string.Empty;
    }

Upvotes: 1

JSteward
JSteward

Reputation: 7091

To display just hours/minutes/seconds use this format string:

var timeSpent = new TimeSpan(1, 12, 23, 62);
Console.WriteLine(timeSpent.ToString(@"hh\:mm\:ss"));

You can find more info here

Upvotes: 7

Vytautas Plečkaitis
Vytautas Plečkaitis

Reputation: 861

var str = string.Format("{0:00}:{1:00}:{2:00}", timeSpent.Hours, timeSpent.Minutes, timeSpent.Seconds);
_logger.Debug(str);

should do the trick

Upvotes: 4

Related Questions