显示两个日期时间值之间的差异(以小时为单位)
我正在从数据库中检索两个日期时间值。检索到该值后,我需要两个值之间的差异。 为此,我创建一个时间跨度变量来存储两个日期值的差异。
TimeSpan? variable = datevalue1 - datevalue2;
现在我需要显示存储在 Timespan 变量中的小时数差异。 我提到了 TimeSpan.TotalHours 但由于某种原因无法应用相同的方法。 我该怎么做? 我在 MVC 项目中使用 C#。我只是需要显示以小时为单位的差异值?
编辑: 由于时间跨度可为空,因此我无法使用总小时数属性。现在我可以通过执行 TimeSpanVal.Value.TotalHours; 来使用它
I am retrieving two date time values from the database. Once the value is retrieved, I need the difference between the two values.
For that, I create a timespan variable to store the difference of the 2 date values.
TimeSpan? variable = datevalue1 - datevalue2;
Now i need to show the difference which is stored in the Timespan variable in terms of number of hours.
I referred to TimeSpan.TotalHours but couldn't apply the same for some reason.
How do I do that?
I am using C# on a MVC project. I simple need to show the difference value in hours?
EDIT:
Since timespan was nullable, i couldn't use the total hours property. Now I can use it by doing TimeSpanVal.Value.TotalHours;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
你可能还想看看
you may also want to look at
我认为您很困惑,因为您没有声明
TimeSpan
您已经声明了TimeSpan?
这是一个 可空TimeSpan
。如果您不需要将问号设为可为空,请删除问号,或者使用variable.Value.TotalHours
。I think you're confused because you haven't declared a
TimeSpan
you've declared aTimeSpan?
which is a nullableTimeSpan
. Either remove the question mark if you don't need it to be nullable or usevariable.Value.TotalHours
.在示例中,我们创建两个日期时间对象,一个包含当前时间,另一个在当前时间基础上添加了 75 秒。然后我们将在第二个 DateTime 对象上调用 .Subtract() 方法。这将返回一个 TimeSpan 对象。
一旦我们获得了 TimeSpan 对象,我们就可以使用 TimeSpan 的属性来获取实际的小时、分钟和秒。
结果:
In the sample, we are creating two datetime objects, one with current time and another one with 75 seconds added to the current time. Then we will call the method .Subtract() on the second DateTime object. This will return a TimeSpan object.
Once we get the TimeSpan object, we can use the properties of TimeSpan to get the actual Hours, Minutes and Seconds.
Result:
您使用
Nullable
有什么原因吗?如果您想使用
Nullable
,那么您可以编写variable.Value.TotalHours
。或者您可以直接编写:
(datevalue1 - datevalue2).TotalHours
。Is there a reason you're using
Nullable
?If you want to use
Nullable
then you can writevariable.Value.TotalHours
.Or you can just write:
(datevalue1 - datevalue2).TotalHours
.这是在 C# 中减去两个日期的另一个示例...
Here is another example of subtracting two dates in C# ...
员工付费时间或其他精确要求的更精确方式::
https://dotnetfiddle.net /tVIoVJ
a more precise way for employee paid hours or other precision requirement::
https://dotnetfiddle.net/tVIoVJ
如果我们比较两个不同的日期,还可以添加日期之间的差异
can also add difference between the dates if we compare two different dates
哇,我必须说:保持简单:
并且:
DateTime 对象具有处理布尔结果的所有内置逻辑。
WOW, I gotta say: keep it simple:
and:
The DateTime object has all the builtin logic to handle the Boolean result.