如何才能获得时间差异 [英] How to get difference between times only

查看:182
本文介绍了如何才能获得时间差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想在两个值之间只有时差,当我跨越12个小时时,它给出错误的值。

I want only time difference between two values, it gives the wrong value when I cross 12 hours.

例如:6:00 AM,并选择7:00 PM然后将结果作为660分钟而不是780.
它可以工作,直到我选择12小时范围之间的时间。

ex: 6:00 AM and select 7:00 PM then gives result as 660 minute instead of 780. it works till I select time between 12 hours range.

请帮我解决这个问题。 p>

Please help me to resolve this stuff.

Dim sDateStart As DateTime = Convert.ToDateTime(CType(cboStartHours.SelectedItem, ListItem).ItemText & ":" _
                          & CType(cboStartMins.SelectedItem, ListItem).ItemText & ":00 " _
                          & CType(cboStartAMPM.SelectedItem, ListItem).ItemText)
Dim sDateEnd As DateTime = Convert.ToDateTime(CType(cboEndHours.SelectedItem, ListItem).ItemText & ":" _
                          & CType(cboEndMins.SelectedItem, ListItem).ItemText & ":00 " _
                          & CType(cboEndAMPM.SelectedItem, ListItem).ItemText)
Dim TS As TimeSpan = sDateEnd - sDateStart

Console.WriteLine(TS.Duration.TotalMinutes)

谢谢

推荐答案

如果您只想要两个 DateTime 值之间的时差,可以忽略日期部分通过使用 DateTime.TimeOfDay ,它返回一个 TimesSpan

If you only want the time difference between two DateTime values, you can ignore the date part by using DateTime.TimeOfDay, which returns a TimesSpan.

所以你得到这样的差异:

So you get the difference like so:

var diff = sDateEnd.TimeOfDay - sDateStart.TimeOfDay;

如果差额为负数,则需要添加24小时(例如,如果开始日期有时间为16:00,结束时间为09:00,您将获得-07:00的差异,当您添加24小时后,您将获得17:00的正确结果。

If the difference is negative, you need to add 24 hours to it (for example, if the start date had a time of 16:00 and the end a time of 09:00 you would get a difference of -07:00. When you add 24 hours to that, you get the correct result of 17:00.

例如:

DateTime date1 = new DateTime(2014, 01, 01, 16, 0, 0); // In the afternoon of day 1.
DateTime date2 = new DateTime(2014, 01, 02, 09, 0, 0); // In the morning of day 2.

var diff = date2.TimeOfDay - date1.TimeOfDay;

if (diff.TotalSeconds < 0)
    diff = diff + TimeSpan.FromDays(1);

Console.WriteLine(diff.TotalHours); // Prints 17

如果您的 DateTime 值保证不超过24小时,您可以随时执行此操作:

If your DateTime values are guaranteed to be less than 24 hours apart you can always do this:

var diff2 = (date2 - date1); // Much simpler, but needs DateTime values less than a day apart.

有一个重要的问题:如果DateTime值超过24小时,你想做什么?在这种情况下,产生不到24小时的答案是什么意思?

There is one important question though: What do you want to do if the DateTime values are more than 24 hours apart? What does it mean to produce an answer that is less than 24 hours in that case?

这篇关于如何才能获得时间差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆