【问题标题】:C# Clock In / Clock Hour - Total Time WorkedC# 打卡 / 时钟小时 - 总工作时间
【发布时间】:2020-10-23 03:41:03
【问题描述】:

问题:创建一个包含打卡按钮、打卡按钮和标签的程序来保存总工作时间。

这段代码看起来应该很简单,但我知道我遗漏了一些东西。我无法从 inButton 单击中获取 DateTime clockIn,以便在 outButton 单击中与 TimeSpan 一起使用。我对 C# 很陌生,所以欢迎任何批评。谢谢!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TimeClock
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void inButton_Click(object sender, EventArgs e)
        {
           DateTime clockIn = DateTime.Now;
        }

        public void outButton_Click(object sender, EventArgs e)
        {
            DateTime clockOut = DateTime.Now;
            TimeSpan timeWorked = clockOut - clockIn;

            string timeWorkedReport = $"Time worked = {timeWorked.Hours} hours, {timeWorked.Minutes} minutes";

            timeLabel.Text = timeWorkedReport;
        }
    }
}

【问题讨论】:

  • 局部变量 vs 类数据成员.. ehh
  • 只能假设totalTimeWorked 应该是简单的clockout-clockin,但不是吗?作业是否说明了这一点?
  • 哦,对于你的下一个问题:我想这会给你一个编译错误。如果您有一个或在其他情况下可能是一个例外,请始终在您的问题中包含这些。
  • 注意,在这种情况下您应该使用DateTimeOffset,而不是DateTime。否则,如果在时钟输入/输出时间之间存在 DST 转换,您将得到不正确的结果。或者,您可以使用clockOut.ToUniversalTime() - clockIn.ToUniversalTime(),或者您可以在UTC 中记录您的时间,然后使用DateTime.UtcNow

标签: c# datetime timespan buttonclick


【解决方案1】:

最重要的是,您需要了解变量范围和数据成员。

不太重要 - 以下将起作用:

我刚刚将您的变量提升为类数据成员。

public partial class Form1 : Form
    {
        DateTime clockIn = DateTime.Min;  // Move Here

        public Form1()
        {
            InitializeComponent();
        }

        public void inButton_Click(object sender, EventArgs e)
        {
           clockIn = DateTime.Now;
        }

        public void outButton_Click(object sender, EventArgs e)
        {
            DateTime clockOut = DateTime.Now;
            TimeSpan timeWorked = clockOut - clockIn;

            string timeWorkedReport = $"Time worked = {timeWorked.Hours} hours, {timeWorked.Minutes} minutes";

            timeLabel.Text = timeWorkedReport;
        }
    }

【讨论】:

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