VB.NET Returning sum hours of datetimepicker - vb.net

I have a SELECT that returns a column in datagridview called date and time of datetimepicker and also a column with the flag "input" or "output". I want to return a result with the sum of hours of datetimepicker with the flag "input" and another sum to the flag " ouput ".
Could you help me guys?
Cheers....

But anyway try this to get the sum of time in hours or minutes.
Dim FirstIn As String = CDate(dtp1.value.date).ToString("HH:mm") 'try with or without cdate.
Dim FirstOut As String = CDate(dtp2.value.date).ToString("HH:mm") 'try with or without cdate.
Dim elapsedTime As TimeSpan = DateTime.Parse(FirstOut).Subtract(DateTime.Parse(FirstIn))
Dim elapsedMinutesText As String = elapsedTime.Minutes.ToString()
Dim elapsedHrsText As String = elapsedTime.Hours.ToString * 60
Dim totalMinute As String = CInt(elapsedMinutesText) + CInt(elapsedHrsText)
'then try to isert it to txtbox or message box to see the result.
'but now you can get the minutes and total hours of it.
Hope this it what you want.

Related

Get first and last day from .csv with VB.Net

I have two properties
Property FirstDayOfCsv As String
Property LastDayOfCsv As String
I want that properties obtains min and max values from parsed csv file. Values are days in "dd" format from date column. Now my code looks like this:
Dim csv As String() = IO.File.ReadAllLines("my.csv").Skip(1).ToArray
For Each line In csv
Dim col = line.Split(";"c)
Dim days As Date = col(2)
FirstDayOfCsv = days.ToString("dd").Min
LastDayOfCsv = days.ToString("dd").Max
Next
Unfortunately Min and Max doesn't return values, which I need and I'm stucking here. How to get them?
One option that you have is to add the values to a collection, but converting the String values to Integer values first. Then once you're finished iterating over the lines you would call Min/Max.
Dim csv = IO.File.ReadAllLines("my.csv").Skip(1).ToArray()
Dim everyday = New List(Of Integer)()
For Each line In csv
Dim col = line.Split(";"c)
Dim days = col(2)
Dim daysAsInt As Integer
If (Integer.TryParse(days, daysAsInt)) Then
everyday.Add(daysAsInt)
End If
Next
FirstDayOfCsv = everyday.Min()
LastDayOfCsv = everyday.Max()

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).

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

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.

How to Convert Integer to Date?

Is it possible to convert integer to date? I am using a datagridview where users can type a combinations of number (e.g 07191993) when in editmode then after the user is done editing, the program should format it in date (07-19-1993).
To get a date from the number inputed by user :
Dim theDate = DateTime.ParseExact (input, "MMddyyyy", CultureInfo.InvariantCulture) ' or some other specific CultureInfo / FormatProvider)
To display the date as wanted (if given FormatProvider doesn't do it by itself) :
Dim repr = theDate.ToString ("MM-dd-yyyy")
Create an event for CellEndEdit of datagridview and put in this code
Dim n As Integer = 'Datagridview cell value'
Dim mon As Integer = Convert.ToInt32(n.ToString.Substring(0, 1))
Dim dt As Integer = Convert.ToInt32(n.ToString.Substring(1, 2))
Dim yr As Integer = Convert.ToInt32(n.ToString.Substring(3, 4))
Dim dt1 As New DateTime(yr, mon, dt)
hope this helps.