C# 从负值到正对流的时间跨度差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8923139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TimeSpan difference from negative value to positive convestion
提问by Romilton Fernando
TimeSpan Earlybeforetime = new TimeSpan();
Earlybeforetime = earlybefore.Subtract(Convert.ToDateTime(outtime);
Sometimes it returns a negative value. How do I convert the value to be always positive?
有时它返回一个负值。如何将值转换为始终为正值?
采纳答案by V4Vendetta
You could use Negate()to change the negative value to positive
您可以使用Negate()将负值更改为正值
From MSDN
来自MSDN
If the date and time of the current instance is earlier than value, the method returns a TimeSpan object that represents a negative time span. That is, the value of all of its non-zero properties (such as Days or Ticks) is negative.
如果当前实例的日期和时间早于 value,则该方法返回表示负时间跨度的 TimeSpan 对象。也就是说,其所有非零属性(例如天数或刻度)的值为负。
So you could call the Negate method depending on which value is greater and obtain a positive Timespan
因此,您可以根据哪个值更大来调用 Negate 方法并获得正数 Timespan
Say we have startDateand endDate(endDate is greater than startDate), so when we do
startDate.Subtract(endDate)we would get a negative TimeSpan. So based on this check you could convert the negative value. So if your outtime is ahead of earlybefore it would give you a negative TimeSpan
假设我们有startDate和endDate(endDate 大于 startDate),所以当我们这样做时,
startDate.Subtract(endDate)我们会得到一个负数TimeSpan。因此,基于此检查,您可以转换负值。因此,如果您的超时时间提前,那么它会给您一个负的 TimeSpan
EDIT
编辑
Please check Duration()of the TimeSpanthis should give you the absolute value always
请检查Duration()的TimeSpan这应该给你总是绝对值
Earlybeforetime.Duration()
Earlybeforetime.Duration()
回答by Thaven
Negative values are returned when yours Earlybeforetime is earlierthat outtime. if you want to have absolute "distance" between two points in time, you can use TimeSpan.Duration method, e.g:
当您的 Earlybeforetime早于该超时时间时,将返回负值。如果你想在两个时间点之间有绝对的“距离”,你可以使用 TimeSpan.Duration 方法,例如:
TimeSpan first = TimeSpan.FromDays(5);
TimeSpan second = TimeSpan.FromDays(15);
TimeSpan final = first.Subtract(second).Duration();
Console.WriteLine(final);
this method will return absolute TimeSpan value.
此方法将返回绝对 TimeSpan 值。
回答by Balachandar Palanisamy
var startTime = new TimeSpan(6, 0, 0); // 6:00 AM
var endTime = new TimeSpan(5, 30, 0); // 5:30 AM
var hours24 = new TimeSpan(24, 0, 0);
var difference = endTime.Subtract(startTime); // (-00:30:00)
difference = (difference.Duration() != difference) ? hours24.Subtract(difference.Duration()) : difference; // (23:30:00)
can also add difference between the dates if we compare two different dates times the 24 hours new TimeSpan(24 * days, 0, 0)
如果我们比较两个不同的日期和 24 小时,也可以添加日期之间的差异 new TimeSpan(24 * days, 0, 0)

