C# TimeSpan.Milliseconds 格式化为2位数字

C# TimeSpan.Milliseconds formated to 2 digits

我有一个要显示的计时器 minutes:seconds:hundreds of seconds。 由于 C# timespan 没有获取数百但只有毫秒的方法,我需要以某种方式格式化它。

TimeSpan ts = stopWatch.Elapsed;
currentTime = String.Format("{0:00}:{1:00}:{2:00}", ts.Minutes, ts.Seconds, Math.Round(Convert.ToDecimal(ts.Milliseconds),2));
ClockTextBlock.Text = currentTime;

我试过 Math.Round 但没有任何反应。结果仍然是 1-3 位数字,如下所示:

01:12:7
01:12:77
01:12:777

我希望格式始终像

01:12:07
01:12:77

你可以使用custom TimeSpan format string(这里我们只显示毫秒的前两位数字ff,代表百分之一):

ClockTextBlock.Text = ts.ToString("mm\:ss\:ff");

你需要:

String.Format(@"Time : {0:mm\:ss\.ff}", ts)

其中 "ts" 是您的 TimeSpan 对象。您也可以随时将其扩展到包括小时数等。fff 内容是第二个分数的有效位数

由于毫秒是 1/1000 秒,您只需将毫秒除以 10 即可得到 100 秒。如果您担心四舍五入,那么只需在除法之前手动进行即可。

    int hundredths = (int)Math.Round((double)ts.Milliseconds / 10);

    currentTime = String.Format("{0}:{1}:{2}", ts.Minutes.ToString(D2), ts.Seconds.ToString(D2), hundredths.ToString(D2);

    ClockTextBlock.Text = currentTime;

您可以设置 DateTime 类型时区并加上 Timespan 跨度。 你会得到一个日期时间并格式化它!

  DateTime timezone = new DateTime(1, 1, 1);

  TimeSpan span = stopWatch.Elapsed;

  ClockTextBlock.Text=(timezone + span).ToString("mm:ss:ff");

只需将格式放入 toString 中,它就会简单地向您显示所需的格式:)

        Stopwatch s2 = new Stopwatch();
        s2.Start();
        Console.WriteLine(s2.Elapsed.ToString(@"hh\:mm\:ss"));