Calculating time difference in seconds - vb.net

I am using following code to calculate time difference. I want to display it in seconds, not in HH:MM:SS
Please advise.
Dim myTime = DateTime.Parse("15:40:00 PM")
Dim vrNowTime = DateTime.Parse(TimeOfDay)
Dim result = vrNowTime - myTime
Label1.Text = vrNowTime & " " & myTime
MsgBox(result.ToString)
Thanks

Use result.TotalSeconds (and round it if you want an integer number to be displayed).
Also you may want to write simply:
Dim result as TimeSpan = Now() - myTime

You can also use
Dim Result = DateDiff(DateInterval.Second,Time1,Time2)

Related

Strange Date Parsing Results

I am trying to make a small helper app to assist in reading SCCM logs. Parsing the dates has been pretty straightforward until I get to the timezone offset. It is usually in the form of "+???". literal example: "11-01-2016 11:44:25.630+480"
DateTime.parse() handles this well most of the time. But occasionally I run into a time stamp that throws an exception. I cannot figure out why. This is where I need help. See example code below:
Dim dateA As DateTime = Nothing
Dim dateB As DateTime = Nothing
Dim dateStr_A As String = "11-07-2016 16:43:51.541+600"
Dim dateStr_B As String = "11-01-2016 11:44:25.630+480"
dateA = DateTime.Parse(dateStr_A)
dateB = DateTime.Parse(dateStr_B)
MsgBox(dateA.ToString & vbCrLf & dateB.ToString)
IF run it would seem dateStr_B is an invalid time stamp? Why is this? I've tried to figure out how to handle the +480 using the 'zzz' using .ParseExact() format as shown here Date Formatting MSDN
Am I missing something with the timezone offset? I've searched high and low but these SCCM logs seem to use a non standard way of representing the offset. Any insight would be greatly appreciated
The problem is that +480 is indeed an invalid offset. The format of the offset from UTC (as produced when using the "zzz" Custom Format Specifier) is hours and minutes. +600 is 6 hours and 0 minutes ahead of UTC, which is valid. +480 would be 4 hours and 80 minutes ahead of UTC, which is invalid as the number of minutes can't be more than 59.
If you have some external source of date and time strings that uses an offset that is simply a number of minutes (i.e. +600 means 10 hours and +480 means 8 hours), you will need to adjust the offset before using DateTime.Parse or DateTime.ParseExact.
[Edit]
The following function takes a timestamp with a positive or negative offset (of any number of digits) in minutes, and returns a DateTime. It throws an ArgumentException if the timestamp is not in a valid format.
Public Function DateTimeFromSCCM(ByVal ts As String) As DateTime
Dim pos As Integer = ts.LastIndexOfAny({"+"c, "-"c})
If pos < 0 Then Throw New ArgumentException("Timestamp must contain a timezone offset", "ts")
Dim offset As Integer
If Not Integer.TryParse(ts.Substring(pos + 1), offset) Then
Throw New ArgumentException("Timezone offset is not numeric", "ts")
End If
Dim hours As Integer = offset \ 60
Dim minutes As Integer = offset Mod 60
Dim timestamp As String = ts.Substring(0, pos + 1) & hours.ToString & minutes.ToString("00")
Dim result As DateTime
If Not DateTime.TryParse(timestamp, result) Then
Throw New ArgumentException("Invalid timestamp", "ts")
End If
Return result
End Function
Thank you for the insight. I had a feeling I would need to handle this manually. I just wanted to make sure I wasn't missing something simple in the process. My knowledge of the date and time formatting is a bit lacking.
As such, I have altered my code so that it handles the offset. Granted I will have to add some more input validation in the final product.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dateA As DateTime = Nothing
Dim dateB As DateTime = Nothing
Dim dateStr_A As String = correctOffset("11-07-2016 16:43:51.541+600")
Dim dateStr_B As String = correctOffset("11-07-2016 16:43:51.541+480")
dateA = DateTime.Parse(dateStr_A)
dateB = DateTime.Parse(dateStr_B)
MsgBox(dateA.ToString & vbCrLf & dateB.ToString)
End Sub
Public Function correctOffset(ByVal ts As String)
Dim offset As Integer = CInt(ts.Substring(ts.Length - 3))
Dim offHour As Integer = offset / 60
Dim offMin As Integer = offset - (offHour * 60)
Dim strhour As String = Nothing
Dim strmin As String = Nothing
If offHour <= 9 Then
strhour = "0" & CStr(offHour)
Else
strhour = CStr(offHour)
End If
If offMin <= 9 Then
strmin = "0" & CStr(offMin)
Else
strmin = CStr(offMin)
End If
Return ts.Substring(0, ts.Length - 3) & strhour & ":" & strmin
End Function

Subtracting Hours and Minutes from DateTime not working

I am trying to subtract hours and minutes from a DateTime variable and I have found other posts that show that you should be able to use the .AddHours(-3) in order to achieve this but it is not working for me. I am grabbing the datetime from a DateTimePicker control in vb.net. say the time is 10:00 AM, I want to subtract 3 hours from this to make it 7:00 AM. My hours variable evaluates to -3 but even when I just literally put the number -3 inside the .AddHours it still does not subtract the time. Heres the code
Dim ApptTime As DateTime = Convert.ToDateTime(DateTimePicker2.Value)
Dim travelTime As String = Label60.Text
Dim newtime As Double
Dim split() As String = travelTime.Split(" ")
If split.Length = 2 Then
Dim Minutes As String = split(0).Replace("mins", "")
Else
Dim Hours As Double = split(0).Replace("Hours", "")
Dim Minutes As Double = split(2).Replace("mins", "")
Hours = -Hours
Minutes = -Minutes
ApptTime.AddHours(Hours)
ApptTime.AddMinutes(Minutes)
Label62.Text = (ApptTime.ToString)
It's simple error ...
Dim ApptTime As DateTime = Now
'ApptTime.Subtract(New TimeSpan(1, 60, 60)) 'won't work
ApptTime = ApptTime.Subtract(New TimeSpan(1, 60, 60)) '1h , 60m , 60s
Try this:
Dim NowMinusThreeHours = DateAdd(DateInterval.Hour, -3, Now)

Converting a string to a DateTime in VB.net

I am writing an application to take SNMP data from an APC UPS and I want to do something with that data.
A few of the bits of information that I'm getting come in this format:
0d 2h 5m 45s 0ms
I want to be able to do something if that value goes under 30 minutes (total time - including the days and hours).
If I can get that string to be converted into a DateTime, then I can perform calculations on it.
I guess I'm looking to add that string to Now()... that way I can query how far in the future it is.
I hope that makes sense?
In my head the code looks something like this:
Dim timeNow As DateTime = Now
Dim snmpRuntimeRemaining As DateTime = Now + snmpDataTime
Dim runtimeRemaining As TimeSpan = snmpRuntimeRemaining - timeNow
If runtimeRemaining.TotalMinutes >= 30 Then Do Something
To add to .Now():
var t = new TimeSpan(days, hours, minutes, seconds, milliseconds);
var d = DateTime.Now + t;
Days, hours etc. you can get using a named Regex groups:
var r = new Regex(#"(?<days>\d+)d (?<hours>\d+)h...");
var m = r.Match(input);
var days = m.Groups["days"].Value;
PS You don't need to actually add to .Now, you can just do:
var t1 = (as above)
var t2 = Timespan.FromMinutes(30);
if(t1 < t2) doSth(); // if timespan from string is less (shorter) than 30 minutes
Code is in C#, but I think you can adapt it easily :)
I went a slightly different route away from Regex, and it needs tidying up - but this here is how I did it:
Dim snmpTimeDate As String = "0d 2h 5m 45s 0ms"
Dim split() As String = snmpTimeDate.Split(" ")
Dim days As String = split(0).Replace("d", "")
Dim hours As String = split(1).Replace("h", "")
Dim minutes As String = split(2).Replace("m", "")
Dim seconds As String = split(3).Replace("s", "")
Dim miliseconds As String = split(4).Replace("ms", "")
Dim snmpToTimeSpan = New TimeSpan(days, hours, minutes, seconds, miliseconds)
Dim snmpDateTime = DateTime.Now + snmpToTimeSpan
Dim runtimeRemaining As TimeSpan = snmpDateTime - DateTime.Now
If runtimeRemaining.TotalMinutes >= 30 Then Do Something
Thanks to Gerino for his help!

Checking Row by Row in a report

With reference to this question,
Changing Row Colour according to condition
I got familiar with Conditional formatting. However I still face this problem.
I am using this code to convert time into Time in Minutes.
Dim TestString As String
TestString = Me.Duration
Dim TestArray() As String
TestArray = Split(TestString, ":")
Dim Hours As String
Dim Minutes As String
Dim Seconds As String
Dim HoursMinutes As Integer
Dim MinutesMinutes As Integer
Dim SecondsMinutes As Integer
Hours = TestArray(0)
Minutes = TestArray(1)
Seconds = TestArray(2)
HoursMinutes = CInt(TestArray(0)) * 60
MinutesMinutes = CInt(TestArray(1))
SecondsMinutes = CInt(TestArray(2)) / 60
Dim TimeInMinutes As Integer
TimeInMinutes = HoursMinutes + MinutesMinutes + SecondsMinutes
Me.Duration = TimeInMinutes
However, for some reason this is not working.
Have you any ideas how can I do this for seperate rows?
Thanks in advance
ADD:
I tried creating a field for Minutes, the problem is that they will get all the same number.
the below code has a String variable called dateTime which stores the current date and time in this format: 27/08/2013 10:55:52
The dateTime String is getting split into a Variant arr array
Split(dateTime, Chr(32))(1) returns the time 10:55:52 part of the dateTime variable
then Split(Split(dateTime, Chr(32))(1), ":") splits the time into 3 numbers using : (colon) as delimiter
So you end up with with arr holding # of hrs, # of minutes, # of seconds.
The CLng((arr(0) * 60) + arr(1) + (arr(2) / 60)) returns an Integer/Long representation of the calculated time value
Stick the below sub in a fresh module and run it
Sub Convert()
Dim dateTime As String
dateTime = now
Dim arr
arr = Split(Split(dateTime, Chr(32))(1), ":")
MsgBox "The time " & Split(dateTime, Chr(32))(1) & vbCrLf & _
" as Integer is equal to " & CLng((arr(0) * 60) + arr(1) + (arr(2) / 60))
End Sub

Time Duration in VB.NET

Trying to figure out time formatting is absolutely killing me.
When I press a button I collect a start time using:
StartTime = DateTime.Now.ToString("hh.mm.ss.tt")
Then when the calculation is done I have:
EndTime = DateTime.Now.ToString("hh.mm.ss.tt")
What I would like to do is to:
TotalTime = EndTime - StartTime
But to print the time using the format; "?# Hours, ## Minutes, & ## Seconds"
I probably wouldn't use the ToString() function on the StartTime and EndTime variables, since that turns them into strings.
Try this:
Dim StartTime as DateTime = DateTime.Now
'' Do Stuff
Dim EndTime As DateTime = DateTime.Now
Dim TotalTime As TimeSpan = EndTime - StartTime
Me.Text = TotalTime.ToString("hh':'mm':'ss")
Of course, you can skip the TotalTime variable and just calculate it in place:
Me.Text = (EndTime - StartTime).ToString("hh':'mm':'ss")
If you want to calculate durations, you must not use the string type. Use directly the DateTime variables (that is, DateTime.Now). You should get a TimeSpan object when subtracting.
Dim TotalTime As TimeSpan = EndTime - StartTime
Console.WriteLine( _
"{0:#0} Hours, {1:00} Minutes, & {2:00} Seconds", _
Math.Truncate(TotalTime.TotalHours), _
TotalTime.Minutes, _
TotalTime.Seconds _
)
Solution by OP.
LarsTech answer got me thinking about a better solution. I completely forgot that I had datetime.now.tostring. What I ended up going is:
timenow = DateTime.Now
start = DateTime.Now
Dim totaltime As TimeSpan = (timenow - start)
xlWorkSheet201.Cells(3, 9) = "Total Test Time: " & Format(totaltime.Hours, "#0") & " Hours, " & Format(totaltime.Minutes, "#0") & "Minutes, & " & Format(totaltime.Seconds, "00") & "Seconds."