Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 自动获得加班和加班时间_C#_Datetime_Timespan - Fatal编程技术网

C# 自动获得加班和加班时间

C# 自动获得加班和加班时间,c#,datetime,timespan,C#,Datetime,Timespan,你能帮帮我吗?我正在尝试创建一个考勤系统,其中未按时和加班将自动计算,但有一个错误。例如,员工的计划外出时间为晚上11点,加班时间为上午12点,即1小时,但输出为23小时。有人能帮我计算经过的时间吗 string datetime = "12:00 AM"; // this is the time you are going to time out string OUT = "11:00 PM"; // this is your scheduled out DateTime d1 = Conve

你能帮帮我吗?我正在尝试创建一个考勤系统,其中未按时和加班将自动计算,但有一个错误。例如,员工的计划外出时间为晚上11点,加班时间为上午12点,即1小时,但输出为23小时。有人能帮我计算经过的时间吗

string datetime = "12:00 AM"; // this is the time you are going to time out
string OUT = "11:00 PM"; // this is your scheduled out
DateTime d1 = Convert.ToDateTime(datetime);
DateTime d2 = Convert.ToDateTime(OUT); 
TimeSpan ts = d2.Subtract(d1);

MessageBox.Show(ts.TotalHours.ToString()); // output is 23 which is wrong, it must be 1 hour overtime only

如果打印d1和d2次:

d1 time => "09.01.2019 00:00:00". 
d2 time => "09.01.2019 23:00:00".
那么23-0=23是预期结果

顺便说一下,您可以通过在d1时间对象上加1天,然后从d2对象上减去该结果来获得结果:

TimeSpan ts = d1.AddDays(1).Subtract(d2);
Console.WriteLine(ts.TotalHours.ToString());

让我们从命名变量开始,这有助于我们对代码进行推理

// this is the time you are going to time out
DateTime actual = Convert.ToDateTime("12:00 AM");

// this is your scheduled out
DateTime scheduled = Convert.ToDateTime("11:00 PM"); 

TimeSpan overtime = scheduled.Subtract(actual);
我们发现,您首先执行了错误的计算。这将是正确的计算:

TimeSpan overtime = actual.Subtract(scheduled);
当我们这样做时,虽然我们现在有-23小时。这是因为您的实际时间不在计划时间之后。为此,你需要增加一天

试试这个:

// this is the time you are going to time out
DateTime actual = Convert.ToDateTime("12:00 AM").AddDays(1);

// this is your scheduled out
DateTime scheduled = Convert.ToDateTime("11:00 PM"); 

TimeSpan overtime = actual.Subtract(scheduled);

然后得到想要的结果,即1小时。

IMO,为了解决问题,您必须使用实际的datetime对象。 始终记录实际的系统日期时间,而不操纵部分系统日期时间。 对于您的情况,您应该有记录计划工作开始、计划工作完成和实际工作完成的字段 例如,假设其中一名员工在2019年1月10日14:00:00下午2点开始工作,在2019年1月10日23:00:00晚上11点结束工作,并假设她加班一小时。 系统应将实际工作完成时间记录为2019年1月11日00:00:00 12 AM 当你需要计算或找出额外的时间 计算:

基于时间的var(单位:小时)= 实际工时已完成。减去计划工时已完成。总小时数;


希望这有意义。

是的,它给了我一个正确的答案。谢谢,但问题是如果你把时间定在12点和1点,我就错了23点。这个怎么样?是的,我对上午12点和下午12点有意见,先生。我只是想自动计算员工的非工作时间和加班时间,但计算有问题。我找不到it@Manjay提供由datetime、OUT和您的预期小时差resultdatetime=>12:00AM OUT=>11:00PM预期小时=>1组成的示例数据。至少举5个这样的例子。特别有问题cases@Manjay-请不要发布屏幕截图,除非您已将5+个示例作为文本发布。我们需要投入和预期产出。5个以上的例子。谢谢,是的,你是对的。必须包括小时之间的日期,以确定是否已过,非常感谢!你太棒了。现在我可以完成我的工作了,很高兴听到我的回答帮助你解决了问题。干杯如果你能把你的问题翻译成代码就好了。因此,请让我知道:计划工作开始、计划工作完成和实际工作完成的值,然后我们可以为您的问题提出解决方案。对于希望在此提供帮助的人,请提前阅读。OP反复问同样的问题。