零填充TimeSpan.ToString(String)

Wes*_*Wes 2 c# formatting timespan

我想从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;
Run Code Online (Sandbox Code Playgroud)

我的格式字符串是否需要一些工作或者有更好的方法吗?

D S*_*ley 8

TimeSpan.ToString不支持自定义格式字符串,显示总小时数-它可以只显示小时,其具有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);
Run Code Online (Sandbox Code Playgroud)