Strange Date Parsing Results - vb.net

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

Related

Need help getting my points per hour function to work properly

I'm having difficulty getting my function to work right.
This function is supposed to estimate how many points per hour the user would get but instead it shows way too many numbers.
Dim now As DateTime = DateTime.Now
Private Function PointsPerHour(gainedpoints As String, totalpoints As String)
Dim firstvalue = gainedpoints
Dim secondvalue = firstvalue
Dim thirdvalue = totalpoints
Dim varJWG0 As String = "Points: "
Dim varJWG1 As String = thirdvalue
Dim varJWG2 As String = " Points Per Hour: "
Dim varJJM0 As Double = Double.Parse(thirdvalue.Replace(",", String.Empty)) - Double.Parse(secondvalue.Replace(",", String.Empty))
Dim timeSpan As TimeSpan = Now - DateTime.Now.ToLocalTime
Dim dbl_ As Double = varJJM0 / timeSpan.TotalHours * -1.0
Return (Convert.ToString(varJWG0 & varJWG1) & varJWG2) + dbl_.ToString("0.00")
End Function
Even if I do PointsPerHour(9, 91) it still outputs more than 1000.
What am I doing wrong?
So I am not entirely certain what it is that this method is trying to achieve in your current implementation.
Firstly the values firstValue and secondValue are the same, also firstValue does not seem to be used apart from assigning to secondValue, which just seems redundant to me.
The first problem I can see is that you have no time in this function. The timeSpan you are using to hold presumably the totalHours is not holding a useful value. you are subtracting Now from Now.ToLocalTime. You will either get 0 or your timezone offset from this equation.
Basically; assuming your 9, 91 example; you are getting ((91-9)/timeSpan) * -1).
If 9 is the points you are earning per hour, and 91 is total points, then 91/9 = hours. or if you give the hours 9 * hours = 91 (in this case 10.1).

Something is amiss in my timespan code

My code is as follows:
Private Sub tbRcvrDepartTime_textchanged(sender As Object, e As EventArgs) Handles tbRcvrDepartTime.TextChanged
'Converts the 90 Receiver Arrival & Departures Date & Times to a string for comparison
Dim raTime As String = tbRcvrArriveTime.Text 'Takes the Time only String and converts to string
Dim raDate As String = dpRcvrArriveDate.Text 'Takes the DateTimePicker and converts date to string
Dim raDateString = String.Concat(raDate, " ", raTime) 'Puts together the Date & Time into one continuous string
'Dim raDateFormat As String = "MM-dd-yyyy HH:mm" 'Sets the String to Date style Format
Dim raResultDate As Date = CDate(raDateString) 'Finalizes the String for use in below comparison
Dim rdTime As String = tbRcvrDepartTime.Text 'Takes the Time only String and converts to string
Dim rdDate As String = dpRcvrDepartDate.Text 'Takes the DateTimePicker and converts date to string
Dim rdDateString = String.Concat(rdDate, " ", rdTime) 'Puts together the Date & Time into one continuous string
'Dim rdDateFormat As String = "MM-dd-yyyy HH:mm" 'Sets the String to Date Format
Dim rdResultDate As Date = CDate(rdDateString) 'Finalizes the String for use in below comparison
'Checks to see if 2 or more hours have elapsed since Receiver Arrival/Departure Date & Time
Dim elapsedR As TimeSpan = rdResultDate.Subtract(raResultDate)
tbRcvrDepartTime.BackColor = If(elapsedR.TotalMinutes > 120, Color.LightPink, Color.White)
End Sub
Both raTime & rdTime are separate textboxes.
Both raDate & rdDate are datetimepickers.
When I run the code "live" initially the first record I look at is displayed correctly. Once I move to another record, this goes out the window... I get random results where it will not change the backcolor to the proper color if >120 minutes has elapsed. Other times it changes the backcolor when there is <120 minutes elapsed. Sometimes no change in backcolor when it should or it will change color when it should not. I attempted to originally do this using TotalHours but met with the same results. It is random and is not consistent. I have worked on this for 2 days now with no difference in results. My thinking is there needs to be a way to "refresh" the rdResultDate & raResultDate info when each new record is loaded but I am unable to do that with my code knowledge.
The code must be able to take into account if a new date is present - ie raDate: 11/01/2016 and raTime: 23:46 and
rdDate: 11/02/2016 and rdTime: 03:00 - this would exceed 2 hours (or 120 minutes) and should read "True" and change the backcolor as it is over 2 hours (or 120 minutes).
However if the following were true:
raDate: 11/01/2016 and raTime: 23:46 and
rdDate: 11/02/2016 and rdTime: 01:00 this would not exceed 2 hours (or 120 minutes) and should read "False" and would not change the backcolor.
All of this code:
Dim Detention90 As String
Try
If elapsedR.TotalMinutes > 120 Then
Detention90 = "True"
Else
Detention90 = "False"
End If
Select Case Detention90.ToString
Case = "True" : tbRcvrDepartTime.BackColor = Color.LightPink
Case Else : tbRcvrDepartTime.BackColor = Color.White
End Select
Catch ex As Exception
'If a problem occurs, show Error message box
MessageBox.Show("Receiver Arrive Time & Depart Time Elapsed error" & vbCrLf & "Lines 1424-1434")
End Try
condenses down to just this:
Dim elapsedR As TimeSpan = rdResultDate.Subtract(raResultDate)
tbRcvrDepartTime.BackColor = If(elapsedR.TotalMinutes > 120, Color.LightPink, Color.White)
Not sure if it will directly address your issue, but it was a bit too much for a comment and I've found compacting code in this way is often extremely beneficial for tracking down difficult bugs.
But in this case, I suspect the main issue is parsing the datetime values... that you're not always parsing the DateTime value you expect from a given input string. Specifically, you have format string variables raDateFormat and rdDateFormat, but then call Date.Parse() such that these format variables are never used, and you are left at the mercy of whatever the default date format is for your thread, process, or system. If you're on a system that uses a d/m/y order as in the UK instead of the US-style m/d/y, you'll end up with some strange results. You probably want DateTime.ParseExact() instead.

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

VBA convert time

I need to convert time from 14:54 to a double 14+54/60. And i do this with the following code:
Private Function Omzetten(ByVal time As String) As Double
Dim min As Integer, hours As Integer, datum As Date
datum = CDate(time)
min = DatePart("n", datum)
hours = DatePart("h", datum)
Omzetten = hours + min / 60
End Function
But when the time is 26:00 he only gives 2 because 26-24 is 2. So I thought to ad day = DatePart("d", datum), but then he always gives day = 30. Does anyone has a solution?
if its always in the format hours : mins then use the below:
Dim str As String
Dim strSplit() As String
Dim Val As Double
str = "26:00"
strSplit = Split(str, ":")
Val = CInt(strSplit(0)) + CInt(strSplit(1)) / 60
Try the following, I used VB.Net which from above looks like it must be compatible with the newer VBA variants:
Private Function Omzetten(ByVal time As String) As Double
Dim Hours As Integer = CInt(time.Substring(0, time.IndexOf(":")))
Dim Minutes As Integer = CInt(time.Substring(time.IndexOf(":") + 1))
Return Hours + Minutes / 60
End Function
Just as a note you might want to add some extra checks, the above code will for example fail on non-numeric input or if the time doesn't contain a colon. You might want something more like the following to cope with varying inputs:
Private Function Omzetten(ByVal time As String) As Double
Dim Hours As Integer = 0
Dim Minutes As Integer = 0
Dim HoursStr As String
If time.IndexOf(":") = -1 Then
HoursStr = time
Else
HoursStr = time.Substring(0, time.IndexOf(":"))
End If
If IsNumeric(HoursStr) Then
Hours = CInt(HoursStr)
End If
If time.IndexOf(":") >= 0 Then
Dim MinutesStr As String = time.Substring(time.IndexOf(":") + 1)
If IsNumeric(MinutesStr) Then
Minutes = CInt(MinutesStr)
End If
End If
Return Hours + Minutes / 60
End Function
I think you can achieve this with basic Excel formulas.
As times are stored as numbers if you divide any time by 1/24 (i.e. an hour) you'll get the answer as a double.
Note - if you want to use times over 24 hrs (e.g. 26:00) then set the cell custom format to [h]:mm:ss
Examples
A B
1 14:54 =A1/(1/24) // = 14.9
2 26:00 =A1/(1/24) // = 26.0
Does this help?

how to avoid the changing the date in vb.net

I would like to ask about how to code datetime in CONSOLE vb.net. I already got the format but my problem is after I inputted another data today to the database.
In this image,my data retrieval was error. The ID (1,2,3,4,5,6)should be jan 2. Unfortunately, the output was today after Ive put new data to the database. I was confused on how to code to avoid changing the date.
this is my code:
Dim datetoday As DateTime = DateTime.Now
Dim dateyesterday As DateTime = DateTime.Today
Dim format As String = "yyyy d MMM"
Sub Main()
s = New Sessions
ds = s.GetSession("select CLIENTID, SESSIONCOST from SESSIONS ORDER BY CLIENTID ASC")
Dim startVal = 0
Dim endVal = ds.Tables(0).Rows.Count
For var = startVal To endVal - 1
Console.WriteLine(ds.Tables(0).Rows(var)("CLIENTID").ToString() + " " + ds.Tables(0).Rows(var)("SESSIONCOST").ToString() + " " + datetoday.ToString(format)) 'code for display id and name
Next
Im hoping for you feedback. A sample code would be enough to understand. Thank you
Having the code in your original post is much better - but have you actually read what you've written?
Dim datetoday As DateTime = DateTime.Now
Dim dateyesterday As DateTime = DateTime.Today
These two are going to be pretty much the same thing. If you want yesterday, you would need to subtract a day from Now
Console.WriteLine(ds.Tables(0).Rows(var)("CLIENTID").ToString() + " " + ds.Tables(0).Rows(var)("SESSIONCOST").ToString() + " " + datetoday.ToString(format)) 'code for display id and name
Also - it doesn't appear that you are retrieving (or even storing?) the date in your database. If you are simply printing out the result of DateTime.Now then the date printed next to each row will always be the current date, and not necessarily when the object was created.
Try to use UTC dates (DateTime.UtcNow) in both your app and in your datastore. Only format it with the timezone adjusted date when displaying to a user.