将格式化的TimeSpan显示为字符串

时间:2022-10-30 15:45:45

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

我想显示TimeSpan值,格式为mm:ss(分钟,秒)。

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.

我想知道这是否是正确的代码。我看到其他示例显示了这种技术,但我不确定在DateTime的MinValue中添加内容的原因是什么。

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

为什么不能使用此代码?它似乎产生了有效的结果。

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

1 个解决方案

#1


0  

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

您不需要DateTime来格式化TimeSpan。你可以简单地使用timespan ToString()方法:

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

Also see Link.

另见链接。

#1


0  

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

您不需要DateTime来格式化TimeSpan。你可以简单地使用timespan ToString()方法:

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

Also see Link.

另见链接。