Reputation: 35
How would you convert a randomly generated time into an integer, This is how I have formatted my time;
StartTime = FormatDateTime(Now, DateFormat.LongTime)
EndTime = FormatDateTime(Now, DateFormat.LongTime)
Diff = (EndTime - StartTime.Subtract(TimeSpan))
So for example Diff = "08:30:12"
I want to be able to convert that to "8.30" as in 8 hours and 30 minutes.
Upvotes: 1
Views: 12464
Reputation: 404
You could use the DateTime.DiffDate function, which returns a long
dim date1 as DateTime = Now
dim date2 as DateTime = Now.AddSeconds(-30600) ' 8.5 hours ago
dim lHr as long = DateDiff(DateInterval.Hour, date1, date2) '=-8
dim lMn as long = DateDiff(DateInterval.Minute, date1, date2) '=-510
lHr = DateDiff(DateInterval.Hour, date2, date1) ' = +8
lMn = DateDiff(DateInterval.Minute, date2, date1) ' = +510
(there are other intervals, days, seconds etc. in DateDiff which would also come in handy) Note that there is no rounding up of your values. Makes number of minutes within hour easy
num_Minutes_Past_Hour = lMn - lHr * 60 ' = 30
Upvotes: 0
Reputation: 216243
You say you want an integer representation of your Diff result.
Supposing that Diff is a TimeSpan structure, why not use simply?
Dim x as Integer
x = Convert.ToInt32(Diff.TotalMinutes)
Of course I assume that the difference is never so big to overflow the integer
Upvotes: 1
Reputation: 17580
You can do :
Dim d As Decimal
d = Diff.Hours + Diff.Minutes / 100D
100D gives a decimal that is needed for the division. Integer division 30/100 gives 0
Upvotes: 0
Reputation: 460028
8.30 is not an Integer
.
However, you can use the TimeSpan.Hours
and TimeSpan.Minutes
properties with String.Format
if you want a string with the hours and the minutes parts:
String.Format("{0}.{1}", Diff.Hours, Diff.Minutes)
Upvotes: 1