Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.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,在特定情况下,当我试图用hr1减去hr2时,我遇到了问题,例如,当hr1=13:00和hr2=15:00时,结果是02:00。 但是当值为:hr1=22:00和hr2=02:00时,结果是20:00。 结果应该是04:00 TimeSpan ts1 = hr1.Subtract(hr2).Duration(); TextBox1.Text = ts1.ToString(); 我怎样才能解决这个问题呢?我知道你想要什么,但你目前如何尝试实现它毫无意义。22小时减去20小时等于2小时,这是正确

在特定情况下,当我试图用hr1减去hr2时,我遇到了问题,例如,当
hr1=13:00
hr2=15:00
时,结果是
02:00
。 但是当值为:
hr1=22:00
hr2=02:00
时,结果是
20:00
。 结果应该是
04:00

 TimeSpan ts1 = hr1.Subtract(hr2).Duration();
 TextBox1.Text = ts1.ToString();

我怎样才能解决这个问题呢?

我知道你想要什么,但你目前如何尝试实现它毫无意义。22小时减去20小时等于2小时,这是正确的

你可能想要这个:

new DateTime(1, 1, 2, 2, 0, 0) - new DateTime(1, 1, 1, 22, 0, 0)

您不想减去时间跨度,而是想减去日期(本例中为假日期)。

调用
Duration()
将始终导致时间跨度为正。问题在于,您在计算中丢弃了天数。22:00-02:00是20:00。我相信你期望它是04:00,因为02:00代表“明天”。如果你想要的话,你需要计算22:00-(02:00+24:00),它将给你-04:00,当你调用
Duration()

时,它将变成04:00。你试图减去两个时间跨度,或者说持续时间,而不是固定的时间点。你的代码现在说的是,我想从20小时中减去2小时(实际上是20小时)。相反,您需要使用
DateTime
s。最困难的部分是决定你的时间表的日期。我会重新编写代码,使用
DateTime
s,并保留您实际尝试计算的“时刻”

编辑:从
TimeSpan
转换为
DateTime
可能会导致丢失影响结果的信息:

var ts1 = new DateTime (1, 1, 1, hr1.Hours, hr1.Minutes, hr1.Seconds, hr1.Milliseconds) -
          new DateTime (1, 1, 1, hr2.Hours, hr2.Minutes, hr2.Seconds, hr2.Milliseconds);
不同于:

var ts1 = new DateTime (1, 1, 1, hr1.Hours, hr1.Minutes, hr1.Seconds, hr1.Milliseconds) -
          new DateTime (1, 1, 2, hr2.Hours, hr2.Minutes, hr2.Seconds, hr2.Milliseconds);
或:

这就是为什么需要使用
DateTime
来维护“时间点”

var ts1 = new DateTime (1, 1, 2, hr1.Hours, hr1.Minutes, hr1.Seconds, hr1.Milliseconds) -
          new DateTime (1, 1, 1, hr2.Hours, hr2.Minutes, hr2.Seconds, hr2.Milliseconds);