【问题标题】:Stop watch calculation (convert 00:00) to 00:00秒表计算(转换 00:00)到 00:00
【发布时间】:2020-06-07 12:48:54
【问题描述】:

我遇到了一个小问题,它是一个简单的秒表,但我想在每次程序关闭或单击停止时保存最后日期,以计算每次单击开始时的时间,直到我停止制造时间之类的东西。

举个例子:如果我点击今天开始5秒,然后我关闭程序,我想节省5秒。

然后当我重新打开程序时,它从零开始,但总和为 5 秒。

  • 第二次 = 第一次 + 第二次
  • 第二次 = 05+000 ..

如果我点击开始 8 秒,它会变成:

  • 第二次 = 8 + 5 = 13

如果我关闭程序并重新打开它并单击开始 7 秒

  • 秒时间 = 7 + 13 = 20 秒

但我一直将其转换为 ("HH:mm: ss")

原来是这样的

00:00:00 converts to 2/23/2020 12:00:00 AM.

我希望它转换为 00:00:00 没有任何日期(月、年 ...)

因为当我求和时,它给了我错误的数字。

System.Timers.Timer t;
int D, H, m, s;
CultureInfo enUS = new CultureInfo("en-US");
DateTime Drawing;
DateTime Rent;
long Machine_time;

public Form1()
{
        InitializeComponent();
        Rent = Properties.Settings.Default.Drawing_Time;
}

private void Start_Click(object sender, EventArgs e)
{
        t.Start();
}

private void Stop_Click(object sender, EventArgs e)
{
        t.Stop();

        try
        {
            // Drawing = DateTime.ParseExact(textBox1.Text, @"HH:mm:ss", CultureInfo.InvariantCulture);
            Drawing = DateTime.Parse(textBox1.Text);
          //  Drawing = DateTime.Now.ToString( @"HH:mm:ss");
            Console.WriteLine("{0} converts to {1}.", textBox1.Text, Drawing.ToString());
        }
        catch (FormatException)
        {
            Console.WriteLine("{0} is not in the correct format.", textBox1.Text);
        }

        Properties.Settings.Default.Drawing_Time = Drawing;

        long elapsedTicks = Drawing.Ticks ;
        Machine_time = elapsedTicks + Machine_time;
        TimeSpan elapsedSpan = new TimeSpan(Machine_time);
        MessageBox.Show(Drawing.ToString());

        string message = elapsedSpan.ToString();
        MessageBox.Show(message);

        saveSettings();
    }

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
       Properties.Settings.Default.Machine_Time = Machine_Time ;

        saveSettings();
        t.Stop();
        Application.DoEvents();
    }

    public void saveSettings()
    {
        try
        {
            Properties.Settings.Default.Save();
            MessageBox.Show("Saved Settings");
        }
        catch (Exception e)
        {
            MessageBox.Show("Save Settings: " + e);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        t = new System.Timers.Timer();
        t.Interval = 1000;
        t.Elapsed += onTimeEvent;
    }

    private void onTimeEvent(object sender, System.Timers.ElapsedEventArgs e)
    {
        Invoke(new Action(() =>
        { 
            s += 1;

            if (s == 60)
            {
                s = 0;
                m += 1;
            }

            if (m == 60)
            {
                m = 0;
                H += 1;
            }

            if (H == 24)
            {
                H = 0;
                D += 1;
            }

            labelResult.Text = string.Format("{0}:{1}:{2}:{3}", D.ToString().PadLeft(2, '0'), H.ToString().PadLeft(2, '0'), m.ToString().PadLeft(2, '0'), s.ToString().PadLeft(2, '0'));
            textBox1.Text= string.Format("{0}:{1}:{2}",  H.ToString().PadLeft(2, '0'), m.ToString().PadLeft(2, '0'), s.ToString().PadLeft(2, '0'));
        }));
}

【问题讨论】:

  • 如果您使用 Windows 窗体计时器,您就不必调用
  • 是的,你是对的,但我不认为我的问题需要调用。我会重写定时器上的代码,没问题。
  • 确实,我从来没有说过这是问题..

标签: c# stopwatch


【解决方案1】:

感谢指导我的人,是的,我只是将 DateTime 替换为 TimeSpan,但是是的,它有一周的限制,但我可以弄清楚。再次感谢

还有这个修改代码

  private void Stop_Click(object sender, EventArgs e)
    {
        t.Stop();
          try
        {
            Drawing_time =  TimeSpan.Parse (labelResult.Text);
            Console.WriteLine("{0} converts to {1}.", labelResult.Text, Drawing_time.ToString());
        }
        catch (FormatException)
        {
            Console.WriteLine("{0} is not in the correct format.", labelResult.Text);
        }
         Machine_time = Drawing_time + Machine_time;
        Properties.Settings.Default.Machine_Time = Machine_time;
       MessageBox.Show(Drawing_time.ToString());
        string message = "Full Time   " + ((Machine_time)).ToString() + "\n" +"Days   " +((Machine_time.Days)).ToString() + "\n" + "Hours   "+((Machine_time.Hours)).ToString() + "\n"
         + "Minutes  " + ((Machine_time.Minutes)).ToString()+ "\n"+ "Seconds  " + ((Machine_time.Seconds)).ToString();
     MessageBox.Show(message);
        saveSettings();
    }

【讨论】:

    【解决方案2】:

    你的尝试是一个相当复杂的程序,看起来,它是什么......只使用日期时间会更简单:

    private DateTime _startTime = DateTime.MinValue;
    
    public Form1()
    {
            InitializeComponent();
    }
    
    private void Start_Click(object sender, EventArgs e)
    {
            _startTime = DateTime.UtcNow;
    }
    
    private void Stop_Click(object sender, EventArgs e)
    {
            StopStopwatch(true);
    }
    
    private void StopStopwatch(bool showErrorMessages)
    {
            if(_startTime > DateTime.MinValue)
                Properties.Settings.Default.ElapsedTotalSeconds += (DateTime.UtcNow - _startTIme).TotalSeconds;
            else if(showErrormessages)
                MessageBox.Show("Stopwatch isn't running");
    
            _startTIme = DateTime.MinValue; //if minvalue it means the stopwatch isn't running
    }
    
    private void Reset_Click(object sender, EventArgs e)
    {
            Properties.Settings.Default.ElapsedTotalSeconds = 0;
    }        
    
    
    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
            StopStopwatch(false);
            Properties.Settings.Default.Save();
    }
    
    
    //if you want a visual feedback the timer is running, have a timer that you start and stop with the click events, and update a label in its tick event
    private void Timer_Tick(...) //its a windows forms timer, not a system timers timer
    {
            if(_startTIme > DateTime.MinValue){
    
              TimeSpan ts = TimeSpan.FromSeconds(Properties.Settings.Default.ElapsedTotalSeconds);
    
              ts += (DateTime.UtcNow - _startTime);
    
              Label1.Text = ts.ToString();
    
            }
    }
    

    这就是管理这个细节所需的全部内容:

    • 记录有人点击开始的时间

    • 当有人单击停止时,将当前时间减去开始时间,然后从结果时间跨度中得到总秒数。将秒表标记为未运行,因此如果他们再次单击停止,则不会再次添加

    • 将这些秒保存到设置保存中(注意:必须是用户范围设置,应该是双精度类型)

    • 如果他们在计时器运行时退出应用,请停止计时器、添加秒数、保存设置、关闭应用

    提供重置机制。

    如果您想要某种计时器正在运行的视觉反馈,请参阅代码底部 - 它是一个计时器,它会根据 Settings 值使用从 TimeSpan 派生的当前总时间以及 TimeSpan 重复更新标签基于单击开始时间和现在之间的差异。每次计时器响起时,标签都会更新。如果你想让山雀每秒更新 10 次,让定时器间隔 100ms

    【讨论】:

      【解决方案3】:

      我看到您使用DateTime 来保持“累积时间”或已经过去了多少时间。不要为此使用 DateTime。顾名思义,DateTime 用于保留 DATE 和 TIME 部分,当您认为“自 5 天前以来已经过去了多少时间?”您不会用“5 月 5 日”来回答这样的问题。你需要一些不关心日历日期的东西。只是时间本身。

      您要使用的是TimeSpan,这是一个时间间隔,没有日期。这种数据类型简单地描述了已经过去了多少时间。你不会在那里找到“2 月 13 日”,因为月日用于描述时间点,而不是时间间隔。在TimeSpan 中,时间间隔被描述为秒/分钟/小时/天,嗯,就是这样。年/月的长度因各种因素而异,因此它不是时间间隔的好单位。有人可以争辩说“一周”总是 7 天,好吧,我们也可以使用它,但是 TimeSpan 没有周。 dayTimeSpan 中的最后一个单元。

      玩一下TimeSpan,很可能你会自己解决所有问题,并享受更多有趣的编码。

      哦,您可能还想注意可以减去 DateTime。一个日期时间减去另一个日期时间会返回一个 TimeSpan 值。方便。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-24
        • 2014-02-19
        • 1970-01-01
        • 2016-03-18
        • 1970-01-01
        • 1970-01-01
        • 2011-06-27
        相关资源
        最近更新 更多