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

问题描述 投票:0回答:6

我有一个计时器想要展示

minutes:seconds:hundreds of seconds
。 由于 C# 时间跨度没有获取数百秒但只有毫秒的方法,因此我需要以某种方式对其进行格式化。

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
c# visual-studio-2017 timespan
6个回答
5
投票

您需要:

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

其中

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


2
投票

您可以使用自定义 TimeSpan 格式字符串(这里我们仅使用

ff
显示毫秒的前两位数字,代表百分之一):

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

0
投票

您可以设置

DateTime
类型的时区并加上
Timespan
跨度。 您将获得一个日期时间并格式化它!

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

  TimeSpan span = stopWatch.Elapsed;

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

0
投票
TimeSpan ts = stopWatch.Elapsed;
currentTime = timeSpan.ToString(@"mm\:ss\:fff");

-1
投票

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

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

-1
投票

由于毫秒为 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;
© www.soinside.com 2019 - 2024. All rights reserved.