DateTime + Timer Tick?

时间:2013-04-20 10:03:59

标签: c# datetime time

当我点击按钮时,我希望开始“经过时间”。到目前为止我写过这个:

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

timer间隔为1000(1秒)。

我想要的是格式化时间:

HH:MM:SS

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

3 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:1)

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

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

如果您愿意,还可以设置秒表的频率,以最大限度地减少资源消耗。

答案 2 :(得分: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");
}