将 TimeSpan 格式化为小时、分钟和秒

LuD*_*Gon 5 c# datetime

我正在尝试为我的问题找到解决方案,我正在使用 TimeSpan 通过减去两个 Datetime 对象来获取窗口打开的总时间。它正在工作,但我得到了毫秒,我只需要显示小时、分钟和秒。这是我正在使用的代码 _timeStart 在方法外部初始化,但它只是获取窗口打开的时间。

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

JSt*_*ard 6

要仅显示小时/分钟/秒,请使用以下格式字符串:

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

您可以在这里找到更多信息


Vyt*_*tis 3

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

应该能解决问题