Reputation: 1625
I want only time difference between two values, it gives the wrong value when I cross 12 hours.
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.
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)
Thank You
Upvotes: 0
Views: 195
Reputation: 6849
try this also. in VB.Net there is a method that you can use directly to get the difference between two date values in Year/Month/Quarter/Days/Hours/Minutes/Seconds.
Dim iMin As Long = DateDiff(DateInterval.Minute, sDateStart, sDateEnd)
you can find the complete reference and example on msdn
in C#
DateTime sDateStart = New DateTime(2014,07,06,18,0,0); //06-Jul-2014 06:00PM
DateTime sDateEnd = New DateTime(2014,08,08,7,0,0); //08-Aug-2014 07:00AM
TimeSpan ts = sDateEnd - sDateStart;
int iMin = ts.TotalMinutes; //Result of ts.TotalMinutes: 46860.0F
Upvotes: 4
Reputation: 109567
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;
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.
For example:
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
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.
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?
Upvotes: 3