【问题标题】:DateTime + Timer Tick?日期时间 + 计时器滴答声?
【发布时间】:2013-04-20 10:03:58
【问题描述】:

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

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

timer 间隔为 1000(1 秒)。

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

HH:MM:SS

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

【问题讨论】:

    标签: c# datetime time


    【解决方案1】:

    您可以使用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();
    }
    

    【讨论】:

    • 我应该把TimeSpan _elapsed = new TimeSpan();的声明放在哪里?在 timer_Tick 里面它说它在上下文中不存在:O
    • 它应该是你现有类的一个新成员,如果你愿意,你可以把它放在你的 timer_Tick() 方法之上,就像我的例子一样。
    • 我把它放在这里,但它不起作用:O 编辑:_elasped,错误输入 :)
    • 抱歉,我的示例中有错字:_elasped => _elapsed。我已经修好了。
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

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

      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");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多