我有一个HH:mm:ss.fffffff时间盘,例如12:13:08.1265838,我使用这段代码将时间盘格式化为小数点后的一位:
Duration = TimeSpan.Parse(stopEventOut.StopEventDateTime.Subtract(stopEventIn.StopEventDateTime).ToString("hh':'mm':'ss'.'f")),这将代码格式化为小数点后一位,但留下了0。(使用上面的示例可以将格式设置为12:13:08.1000000)
是否有方法在to字符串格式中删除这些内容,或者任何其他方式?
发布于 2022-07-06 13:15:52
您的代码似乎要减去两次日期来生成一个TimeSpan,然后调用.ToString()来格式化结果,然后冗余地将结果解析回TimeSpan。因此,您将内部timespan (12:13:08.1265838)的字符串格式化为"12:13:08.1",然后将其解析回TimeSpan,在那里它变成12:13:08.1000000。
您应该在完成所有timespan计算之后格式化,并消除冗余解析:
Duration = stopEventOut.StopEventDateTime.Subtract(stopEventIn.StopEventDateTime),
// ...
Console.WriteLine(Duration.ToString("hh':'mm':'ss'.'f")); // 12:13:08.1作为一个小小的好处,您可以在TimeSpan上创建一些扩展方法,以相应地格式化时间盘,如下所示:
public static class TimeSpanExtensions
{
public static string WithTenthsOfASecond(this TimeSpan t)
{
return t.ToString("hh':'mm':'ss'.'f");
}
public static string WithHundredthsOfASecond(this TimeSpan t)
{
return t.ToString("hh':'mm':'ss'.'ff");
}
public static string WithMilliseconds(this TimeSpan t)
{
return t.ToString("hh':'mm':'ss'.'fff");
}
} 这样你就可以做:
Duration.WithTenthsOfASecond(); // "12:13:08.1"
Duration.WithHundredthsOfASecond(); // "12:13:08.12"
Duration.WithMilliseconds(); // "12:13:08.126"发布于 2022-07-06 13:04:58
不要使用f,而是使用F。它不会显示任何落后的0。
另外,如果您在调试器中查看Duration --这是默认格式。
https://stackoverflow.com/questions/72884048
复制相似问题