1

当我点击一个按钮时,我想开始一个“经过的时间”。到目前为止,我已经写了这个:

private void timer_Tick(object sender, EventArgs e)
{
    timeCounter++;
    labelTimer.Text = "Elapsed Time: " + timeCounter.ToString();
}

timer间隔为 1000(1 秒)。

我想要的是像这样格式化时间:

HH:MM:SS

并在秒数达到 60 时自动增加分钟数,依此类推数小时。我应该为此使用 DateTime 并每 1 秒添加一秒吗?

4

3 回答 3

5

您可以使用TimeSpan

TimeSpan _elapsed = new TimeSpan();

private void timer_Tick(object sender, EventArgs e)
{
    _elapsed = _elapsed.Add(TimeSpan.FromMinutes(1));
    labelTimer.Text = "Elapsed Time: " + _elapsed.ToString();
}
于 2013-04-20T10:06:39.147 回答
1

您可以使用秒表和经过时间来创建日期时间(并根据需要设置其格式)。

Stopwatch s = Stopwatch.StartNew();
//Some more operations here...
s.Stop();
DateTime t = new DateTime(s.ElapsedTicks);

如果您愿意,您还可以设置秒表的频率,以尽量减少资源消耗。

于 2013-04-20T10:25:46.327 回答
0

您可以像这样使用的简单方法:

private void timer_Tick(object sender, EventArgs e) 
{
       Stopwatch stopWatch = Stopwatch.StartNew();

       // Your logics goes Here

       stopWatch.Stop();
       DateTime time = new DateTime(stopWatch.ElapsedTicks);
       labelTimer.Text = time.ToString("HH:mm:ss");
}
于 2013-04-20T10:43:29.257 回答