I have 1 datagridview named IncomingMailDGV.
Sample data on Contents Column:
R-1 temperature (6.25) rose above high bound SLTCR at Warehouse-1 at 27/07/15 13:40
R-2 temperature (6.62) rose above high bound SLTCR at Store at 27/07/15 13:42
R-3 temperature (6.31) rose above high bound SLTCR at Warehouse-2 at 27/07/15 13:45
Note: Some contents has three spaces on the last part of the message.
I want to get the date and time which is placed on the last part and convert it to this format: "M/dd/yyyy HH:mm tt"
I'm using below code but its not working:
Sub FilterAlert()
Try
Dim Dbcon As New OleDbConnection(connStr)
Dbcon.Open()
For x As Integer = 0 To IncomingMailDGV.Rows.Count - 1
Dim line2 As String = IncomingMailDGV.Rows(x).Cells("Contents").Value.ToString
Dim separators() As String = {",", " ", "(", ")"}
Dim length As Integer = line2.Length
Dim alertdatetime As String
Dim alertdate_time As String
data2 = line2.Split(separators, StringSplitOptions.RemoveEmptyEntries)
alertdate_time = line2.Substring(length - 14, 14)
Dim alertstring = alertdate_time.Split(separators, StringSplitOptions.RemoveEmptyEntries)
alertdatetime = alertstring(0)
alertdatetime = DateTime.ParseExact(alertdatetime, "dd/MM/yyHH:mm", Nothing)
console.writeline (alertdatetime)
Next
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
Update: Some cells on Contents Column are empty.
If you mean that there may be more than one space between the date and the time, then you can just take the last 14 characters from the string. The following code assumes that the date and time are always preceded by " at ". It's not clear what you want to do if the string is not in the correct format, this code simply ignores invalid strings.
Note that DateTime doesn't have a format, it's just numbers. You can use DateTime.ToString to output the date and time in whatever format you want.
This code is intended to replace everything inside the For loop.
Dim line2 As String = IncomingMailDGV.Rows(x).Cells("Contents").Value.ToString
Dim pos As Integer = line2.LastIndexOf(" at ")
If pos < 0 Then Continue For
Dim alertstring() As String = line2.Substring(pos + 4).Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
If alertstring.length <> 2 Then Continue For
Dim alertdatetime As DateTime
If Not DateTime.TryParseExact(alertstring(0) & alertstring(1), "dd/MM/yyHH:mm", _
System.Globalization.CultureInfo.InvariantCulture, Nothing, alertdatetime) Then Continue For
Console.WriteLine(alertdatetime.ToString("M/dd/yyyy HH:mm tt"))
Related
I need to break a variable to get the value of the database. Today my full return would be "2017-09-15T14: 01: 46" I only need 2017-09-15 and 14:01, I tried to do
.Substring (0.10) for the date and worked, already for the time I tried Substring (11,16) and the error that is in the title of the question occurs.
Assuming you always have the capital T in your result string
dim xValue as string = "2017-09-15T14: 01: 46"
dim xStr() as string = xValue.split("T")
dim xDate as string = ""
dim xTime as string = ""
if xstr.count>0 then
xDate = xStr(0)
xTime = xStr(1)
end if
or
dim xValue as string = "2017-09-15T14: 01: 46"
dim xDate as string = strings.left(xValue, 10)
dim xTime as string = strings.mid(xValue, 12)
So with VB.NET, you can use the DateTime method. From the DateTime, you can do something like DateTime.Date or DateTime.ToShortDateString for just the date and DateTime.ToShortTimeString for the time.
Your arguments to the function Substring are wrong.
The second argument to the function Substring (in your case 16) needs to be the amount of letters that the function will return and NOT the index it needs to end in.
It will work with something like Substring(11, 5), where the 5 is the length of the returned substring.
Dim temp_date As String = "2017-09-15T14: 01: 46"
Dim main_date As String = temp_date.Substring(0, 10)
Dim main_time As String = temp_date.Substring(11, 6)
OR
a better approach using the datetime object proposed by AustinS90 (this will support alot of time formatted strings):
Dim temp_date As DateTime = DateTime.Parse("2017-09-15T14: 01: 46")
Dim main_date As String = temp_date.Year() & "-" & temp_date.Month() & "-" & temp_date.Day
Dim main_time As String = temp_date.Hour & ":" & temp_date.Minute
I have three values which need to be sorted from highest to lowest value. I use the following code which works like a charm until I want to use periods "." and commas ",". If I type "1,3" it displays as I like, but if I type "1.3" it changes to 13. My end users need to be able to use both commas and periods.
How can I fix this?
Dim IntArr(2) As Decimal
IntArr(0) = TextBox1.Text
IntArr(1) = TextBox2.Text
IntArr(2) = TextBox3.Text
Array.Sort(IntArr)
Dim highestNum As Decimal
Dim Midelnum As Decimal
Dim lowestNum As Decimal
lowestNum = IntArr(0)
Midelnum = IntArr(1)
highestNum = IntArr(2)
MsgBox("Highest " & highestNum)
MsgBox("lowest " & lowestNum)
MsgBox("middel " & Midelnum)
The problem is that it's based on culture. I say this because if I enter numbers as you described, I get the opposite effect ("1,3" -> "13", etc).
Here's a quick way to change the values to match the current culture.
At the top of your class, put this:
Imports System.Globalization
Then, you can do this:
Dim IntArr(2) As Decimal
Dim nfi As NumberFormatInfo = CultureInfo.CurrentCulture.NumberFormat
Dim sep1 As String = nfi.NumberDecimalSeparator
Dim sep2 As String = If(sep1.Equals("."), ",", ".")
Dim useComma As Boolean = (TextBox1.Text.Contains(",") Or TextBox2.Text.Contains(",") Or TextBox3.Text.Contains(","))
'Replace the separator to match the current culture for parsing
Decimal.TryParse(TextBox1.Text.Replace(sep2, sep1), IntArr(0))
Decimal.TryParse(TextBox2.Text.Replace(sep2, sep1), IntArr(1))
Decimal.TryParse(TextBox3.Text.Replace(sep2, sep1), IntArr(2))
Array.Sort(IntArr)
sep1 = If(useComma, ",", ".")
sep2 = If(useComma, ".", ",")
'Reformat the results to match the user's input
Dim lowestNum As String = IntArr(0).ToString().Replace(sep2, sep1)
Dim middleNum As String = IntArr(1).ToString().Replace(sep2, sep1)
Dim highestNum As String = IntArr(2).ToString().Replace(sep2, sep1)
Dim msg As String = "Highest: {0}" & Environment.NewLine & _
"Lowest: {1}" & Environment.NewLine & _
"Middle: {2}"
msg = String.Format(msg, highestNum, lowestNum, middleNum)
MessageBox.Show(msg)
Also, since you are using .NET, you may want to skip the VB6 way of doing things. Refer to my example to see what I've used.
You could use the hack of altering the string before saving it:
TextBox.Text.Replace(".",",")
But if you want to show the original input you could have a variable to detect the entered character:
Dim isDot As Boolean = False
Dim number As String = TextBox.Text
If number.Contains(".") Then
isDot = True
End If
And in the end replace it just for purposes of displaying
If isDot Then
number.Replace(",",".")
End If
The accepted answer uses too much unnecessary string manipulation. You can use the CultureInfo object to get what you need:
Sub Main
Dim DecArr(2) As Decimal
'Select the input culture (German in this case)
Dim inputCulture As CultureInfo = CultureInfo.GetCultureInfo("de-DE")
Dim text1 As String = "1,2"
Dim text2 As String = "5,8"
Dim text3 As String = "4,567"
'Use the input culture to parse the strings.
'Side Note: It is best practice to check the return value from TryParse
' to make sure the parsing actually succeeded.
Decimal.TryParse(text1, NumberStyles.Number, inputCulture, DecArr(0))
Decimal.TryParse(text2, NumberStyles.Number, inputCulture, DecArr(1))
Decimal.TryParse(text3, NumberStyles.Number, inputCulture, DecArr(2))
Array.Sort(DecArr)
Dim format As String = "Highest: {0}" & Environment.NewLine & _
"Lowest: {1}" & Environment.NewLine & _
"Middle: {2}"
'Select the output culture (US english in this case)
Dim ouputCulture As CultureInfo = CultureInfo.GetCultureInfo("en-US")
Dim msg As String = String.Format(ouputCulture, format, DecArr(2), DecArr(1), DecArr(0))
Console.WriteLine(msg)
End Sub
This code outputs:
Highest: 5.8
Lowest: 4.567
Middle: 1.2
I have a code like this :
Dim mincatval As String
Dim strarr() As String = dr1(0).ToString().Split(New Char() {"-"c})
Dim i As String
i = (Integer.Parse(strarr(0)) + 1)
mincatval = i
my dr(1) value is L1 i want to add 1,so i want the out put L2,but i am getting error like this :Input string was not in a correct format.
Supposing that strarr(0) is the word "L1" and you want it to become "L2" then you need to isolate the numeric part from the text part and then rebuild the string taking the first part of strarr and the incremented value
Dim mincatval As String
Dim strarr() As String = dr1(0).ToString().Split(New Char() {"-"c})
Dim i As String
Dim itShouldBeAnumber = strarr(0).Substring(1)
if Int32.TryParse(itShouldBeAnumber, i) Then
mincatval = strarr(0).Substring(0,1) & (i + 1)
else
MessageBox.Show("Not a valid number from position 1 of " & strarr(0))
End if
Of course this solution assumes that your string is Always composed of an initial letter followed by a numeric value that could be interpreted as an integer
Below is my textbox which i store the output of my serial
Below is where i put the message inside the DataGridView the problem lies here see the last row of the grid there is an OK text.
my last photo shows the value of my line of text.
Dim LineOfText As String
Dim i As Integer
Dim aryTextFile() As String
LineOfText = tt.Text
aryTextFile = Split(LineOfText, "+CMGL", , CompareMethod.Text)
dgv.Rows.Clear()
For i = 1 To UBound(aryTextFile)
'**********************
Dim LineOfTexts As String
Dim aryTextFiles() As String
LineOfTexts = aryTextFile(i)
aryTextFiles = Split(LineOfTexts, """", , CompareMethod.Text)
aryTextFiles(5) = aryTextFiles(5).Substring(0, 17).Replace(",", "-")
dgv.Rows.Add(New String() {aryTextFiles(3), aryTextFiles(6), aryTextFiles(5)})
Next i
is there any other way to extract the message exactly?
aryTextFiles(3) is the phone number/Sender aryTextFiles(6) is the message and aryTextFiles(5) is the date and time.
You can remove the last word by using Trim()
LineOfText = tt.Text.Substring(0, tt.Text.LastIndexOf(vbCrLf) - 3).Trim()
I used -3 to trim the last 3 characters.
I'm looking to parse this text file into strings to insert them into a database.
Source Text File gets read as the following string:
Line of unwanted text
Another line of unwanted data
Timestamp: 1/1/10 12:00 PM
ID: 1
Details: All data processed. Length will vary.
I'd like to just read Timestamp, ID and Details and place them into separate strings to insert them into a data table. What is the best method of capturing everything after the : and to the end of the line?
Dim Details as String = TextFile.Substring(Message.IndexOf("Details:"), X)
If you have to use a String as input, you can use String.Split to break it up into lines, and process each line. String.Substring can be used to extract the rest of the line - I've just hardcoded the starting positions below.
Dim timestamp As String = Nothing
Dim id As String = Nothing
Dim details As String = Nothing
For Each line In input.Split({vbCrLf, vbCr, vbLf}, StringSplitOptions.None)
If line.StartsWith("timestamp:", StringComparison.OrdinalIgnoreCase) Then
timestamp = line.Substring(10).Trim()
ElseIf line.StartsWith("id:", StringComparison.OrdinalIgnoreCase) Then
id = line.Substring(3).Trim()
ElseIf line.StartsWith("details:", StringComparison.OrdinalIgnoreCase) Then
details = line.Substring(8).Trim()
End If
Next
If you can change how you read the data, then the loop could just be:
For each line In File.ReadLines("your\file\name.txt")
...
Next
Assuming your files are flawless... One way to do it :
Imports System.IO
Dim AllLines() As String = File.ReadAllLines(FilePath)
Dim DatasIndex As Int32 = -1
For i As Int32 = 0 To AllLines.Length - 1
If AllLines(i).StartsWith("T") OrElse AllLines(i).StartsWith("t") Then
If AllLines(i).ToUpper().StartsWith("TIMESTAMP: ") Then
DatasIndex = i
Exit For
End If
End If
Next
If DatasIndex > -1 Then
' Dim ReadDate As Date = Date.Parse(AllLines(DatasIndex).Substring(11))
' Dim ReadID As Int32 = Integer.Parse(AllLines(DatasIndex + 1).Substring(4))
Dim ReadDate As String = AllLines(DatasIndex).Substring(11)
Dim ReadID As String = AllLines(DatasIndex + 1).Substring(4)
Dim ReadDetails As String = AllLines(DatasIndex + 2).Substring(9)
' send to database
End If
You didn't tell if Timestamp: , ID: and Details: Strings are always in the same order and has a trailing space after each property name.