我想从TimeSpan对象创建一个字符串,其格式为:“hhhh:mm:ss.ff”。
当我使用以下内容时,我得到一个FormatException ...
private const string MAX_TIME_ALLOWED_FORMAT = @"hhhh\:mm\:ss.ff";
String myDurationSring = TimeSpan.FromSeconds(myDurationInSeconds).ToString(MAX_TIME_ALLOWED_FORMAT) : string.Empty;
我的格式字符串是否需要一些工作,或者有更好的方法吗?
答案 0 :(得分:8)
TimeSpan.ToString
不支持显示总小时数的custom format string - 它只能显示小时部分,其最大值为23。
我使用格式字符串来获取TimeSpan
:
String myDurationSring =
string.Format("{0:0000}:{1:00}:{2:00}.{3:00}",
(int)(ts.TotalHours),
ts.Minutes,
ts.Seconds,
ts.Milliseconds/10.0);
答案 1 :(得分:1)
我认为最简单,最干净的方法是插值:
var myDurationSring = $"{ts.Hours:0000}:{ts.Minutes:00}:{ts:Seconds:00}.{ts.Milliseconds/10.0}";
答案 2 :(得分:-1)
尝试:
"hhhh:mm:ss.ff"
作为格式字符串。我假设你正试图逃避冒号。你不需要。如果您需要输出中的冒号,请尝试:
"hhhh\\:mm\\:ss.ff"