VBA String to Date Conversion, and calculate diff from now() - vba

I'm trying below very simple VBA code to convert to Datetime
Sub datetimedifffference()
Dim d As String
Dim sd As Date
d = "2021-04-06T12:56:16+0000"
sd = Format(CDate(d), "mm-dd-yyyy hh:mm:ss")
Debug.Print sd
End Sub
But it is giving type mismatch error
Any help would be highly appreciated
I again tried below, but the difference of time is decreasing instead increasing
Sub datetimedifffference()
Dim d As String
Dim sd As Long
d = "2021-04-06T12:56:16+0000"
sd = DateDiff("n", Now, Format(convertStringtoDate(d))
Debug.Print sd
End Sub
Function convertStringtoDate(stringdate As String) As String
Dim strings() As String
strings = Split(stringdate, "T")
convertStringtoDate = strings(0) & " " & Left(strings(1), 8)
'Debug.Print convertStringtoDate
End Function

T and +0000 should be replaced. Also note that a date is a number and a formatted date is a String.
Sub datetimedifffference()
Dim d As String
Dim sd As Date
d = "2021-04-06T12:56:16+0000"
d = Replace(d, "T", " ")
d = Replace(d, "+0000", "")
sd = CDate(d)
Debug.Print sd
End Sub

You can use this generic function:
' Converts an ISO 8601 formatted date/time string to a date value.
'
' A timezone info is ignored.
' Optionally, a millisecond part can be ignored.
'
' Examples:
' 2029-02-17T19:43:08 +01.00 -> 2029-02-17 19:43:08
' 2029-02-17T19:43:08 -> 2029-02-17 19:43:08
' ' IgnoreMilliseconds = False
' 2029-02-17T19:43:08.566 -> 2029-02-17 19:43:08.566
' ' IgnoreMilliseconds = True
' 2029-02-17T19:43:08.566 -> 2029-02-17 19:43:08.000
'
' 2017-05-24. Gustav Brock. Cactus Data ApS, CPH.
'
Public Function CDateIso8601( _
ByVal Expression As String, _
Optional ByVal IgnoreMilliseconds As Boolean) _
As Date
Const Iso8601Separator As String = "T"
Const NeutralSeparator As String = " "
' Length of ISO 8601 date/time string like: 2029-02-17T19:43:08 [+00.00]
Const Iso8601Length As Integer = 19
' Length of ISO 8601 date/time string like: 2029-02-17T19:43:08.566
Const Iso8601MsecLength As Integer = 23
Dim Value As String
Dim Result As Date
Value = Replace(Expression, Iso8601Separator, NeutralSeparator)
If InStr(Expression, MillisecondSeparator) <> Iso8601Length + 1 Then
IgnoreMilliseconds = True
End If
If IgnoreMilliseconds = False Then
Result = CDateMsec(Left(Value, Iso8601MsecLength))
Else
Result = CDate(Left(Value, Iso8601Length))
End If
CDateIso8601 = Result
End Function
Then apply the format of yours to the returned value.

Looking at your edit, I think you need to change the order of both dates:
Sub datetimedifffference()
Dim d As String
Dim sd As Long
d = "2021-04-06T12:56:16+0000"
sd = DateDiff("n", convertStringtoDate(d), Now)
Debug.Print sd
End Sub
Function convertStringtoDate(stringdate As String) As String
Dim strings() As String
strings = Split(stringdate, "T")
convertStringtoDate = CDate(strings(0) & " " & Left(strings(1), 8))
End Function

Related

im trying to find the gap between 2 numbers

I'm having trouble finding the gap between 2 numbers for a parking charge. I tried this:
'time for entry
Dim entered As String = txtHourEnter.Text + ":" + txtMinEnter.Text
Dim time As DateTime
Dim display As String = "Invalid entry"
If DateTime.TryParse(entered, time) Then
display = time.ToString("h:mm tt")
End If
lblTimeIn.Text = display
'time for exited
Dim exited As String = txtHourExit.Text + ":" + txtMinExit.Text
Dim out As DateTime
Dim display2 As String = "invalid entry"
If DateTime.TryParse(exited, out) Then
display2 = out.ToString("h:mm tt")
End If
lblTimeOut.Text = display2
'parking time
Dim parkingtime As String = (display - display2)
lblParkingTime.Text = parkingtime
But I get this error:
The OP forgot to include the error message. How embarrassing for them :(
The code was trying to subtract the strings, instead of the timestamps. You need to get actual datetime values and subtract those.
Dim hourEnter As Integer = Int32.Parse(txtHourEnter.Text)
Dim minuteEnter As Integer = Int32.Parse(txtMinEnter.Text)
Dim hourExit As Integer = Int32.Parse(txtHourExit.Text)
Dim minuteExit As Integer = Int32.Parse(txtMinExit.Text)
Dim timeEnter As DateTime = DateTime.Today.AddHours(hourEnter).AddMinutes(minuteEnter)
Dim timeExit As DateTime = DateTime.Today.AddHours(hourExit).AddMinutes(minuteExit)
Dim parkingTime As TimeSpan = timeExit - timeEnter
lblTimeIn.Text = timeEnter.ToString("h:mm tt")
lblTimeOut.Text = timeExit.ToString("h:mm tt")
lblParkingTime.Text = parkingTime.ToString("h:mm")

Convert string to double and add for total

I am relatively new to coding.
I'm trying to figure out why my hours per day aren't converting to numbers that are then added together. Instead they are just taking those strings and writing them as strings and making a huge number.
For example: If I worked 8 hours per day M-F, it displays 88888 instead of 40 (40 hours total for the week). I did convert the strings to a double and then added them together.
Any help is appreciated. I have no teachers to ask on the weekend.
Public Class Form1
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
' Get file
Dim srdFile As System.IO.StreamReader
srdFile = New System.IO.StreamReader("payroll.txt")
' Declarations
Dim strLine, strRecord() As String
Dim strFirst As String
Dim strLast As String
Dim strPayRate As String
Dim strMon As String
Dim strTues As String
Dim strWed As String
Dim strThurs As String
Dim strFri As String
Dim dblTotalHours As Double
Dim dblTotalPay As Double
Dim dblGrandTotalPay As Double
Do Until srdFile.Peek = -1
' Read
strLine = srdFile.ReadLine
strRecord = strLine.Split(",")
strFirst = strRecord(0)
strLast = strRecord(1)
strPayRate = Convert.ToDouble(strRecord(2))
strMon = Convert.ToDouble(strRecord(3))
strTues = Convert.ToDouble(strRecord(4))
strWed = Convert.ToDouble(strRecord(5))
strThurs = Convert.ToDouble(strRecord(6))
strFri = Convert.ToDouble(strRecord(7))
' Processing
dblTotalHours = strMon + strTues + strWed + strThurs + strFri
dblTotalPay = dblTotalHours * strPayRate
dblGrandTotalPay += dblTotalPay
' Output
rtbOut.AppendText(strFirst & " " & strLast & ControlChars.Tab & "rate: $" & strPayRate.ToString & ControlChars.Tab & "hours: " & dblTotalHours.ToString("n") & ControlChars.Tab & "pay: " &
dblTotalPay.ToString("c") & vbNewLine & "Total Pay: " & dblGrandTotalPay.ToString("c") & vbNewLine)
Loop
End Sub
End Class
Because your variables are defined as strings, this code is concatenating the values:
strMon + strTues + strWed + strThurs + strFri
In VB.Net you can concatenate using + or &
Convert these variables to a double data type (to preserve the decimal portion):
Dim strMon As Double
Dim strTues As Double
Dim strWed As Double
Dim strThurs As Double
Dim strFri As Double
Then the + operator will add the variables together.

How can I get String values rather than integer

How To get StartString And EndString
Dim startNumber As Integer
Dim endNumber As Integer
Dim i As Integer
startNumber = 1
endNumber = 4
For i = startNumber To endNumber
MsgBox(i)
Next i
Output: 1,2,3,4
I want mo make this like sample: startString AAA endString AAD
and the output is AAA, AAB, AAC, AAD
This is a simple function that should be easy to understand and use. Every time you call it, it just increments the string by one value. Just be careful to check the values in the text boxes or you can have an endless loop on your hands.
Function AddOneChar(Str As String) As String
AddOneChar = ""
Str = StrReverse(Str)
Dim CharSet As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim Done As Boolean = False
For Each Ltr In Str
If Not Done Then
If InStr(CharSet, Ltr) = CharSet.Length Then
Ltr = CharSet(0)
Else
Ltr = CharSet(InStr(CharSet, Ltr))
Done = True
End If
End If
AddOneChar = Ltr & AddOneChar
Next
If Not Done Then
AddOneChar = CharSet(0) & AddOneChar
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim S = TextBox1.Text
Do Until S = TextBox2.Text
S = AddOneChar(S)
MsgBox(S)
Loop
End Sub
This works as a way to all the codes given an arbitrary alphabet:
Public Function Generate(starting As String, ending As String, alphabet As String) As IEnumerable(Of String)
Dim increment As Func(Of String, String) = _
Function(x)
Dim f As Func(Of IEnumerable(Of Char), IEnumerable(Of Char)) = Nothing
f = _
Function(cs)
If cs.Any() Then
Dim first = cs.First()
Dim rest = cs.Skip(1)
If first = alphabet.Last() Then
rest = f(rest)
first = alphabet(0)
Else
first = alphabet(alphabet.IndexOf(first) + 1)
End If
Return Enumerable.Repeat(first, 1).Concat(rest)
Else
Return Enumerable.Empty(Of Char)()
End If
End Function
Return New String(f(x.ToCharArray().Reverse()).Reverse().ToArray())
End Function
Dim results = New List(Of String)
Dim text = starting
While True
results.Add(text)
If text = ending Then
Exit While
End If
text = increment(text)
End While
Return results
End Function
I used it like this to produce the required result:
Dim alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim results = Generate("S30AB", "S30B1", alphabet)
This gave me 63 values:
S30AB
S30AC
...
S30BY
S30BZ
S30B0
S30B1
It should now be very easy to modify the alphabet as needed and to use the results.
One option would be to put those String values into an array and then use i as an index into that array to get one element each iteration. If you do that though, keep in mind that array indexes start at 0.
You can also use a For Each loop to access each element of the array without the need for an index.
if the default first two string value of your output is AA.
You can have a case or if-else conditioning statement :
and then set 1 == A 2 == B...
the just add or concatenate your default two string and result string of your case.
I have tried to understand that you are looking for a series using range between 2 textboxes. Here is the code which will take the series and will give the output as required.
Dim startingStr As String = Mid(TextBox1.Text, TextBox1.Text.Length, 1)
Dim endStr As String = Mid(TextBox2.Text, TextBox2.Text.Length, 1)
Dim outputstr As String = String.Empty
Dim startNumber As Integer
Dim endNumber As Integer
startNumber = Asc(startingStr)
endNumber = Asc(endStr)
Dim TempStr As String = Mid(TextBox1.Text, 1, TextBox1.Text.Length - 1)
Dim i As Integer
For i = startNumber To endNumber
outputstr = outputstr + ", " + TempStr + Chr(i)
Next i
MsgBox(outputstr)
The First two lines will take out the Last Character of the String in the text box.
So in your case it will get A and D respectively
Then outputstr to create the series which we will use in the loop
StartNumber and EndNumber will be give the Ascii values for the character we fetched.
TempStr to Store the string which is left off of the series string like in our case AAA - AAD Tempstr will have AA
then the simple loop to get all the items fixed and show
in your case to achive goal you may do something like this
Dim S() As String = {"AAA", "AAB", "AAC", "AAD"}
For Each el In S
MsgBox(el.ToString)
Next
FIX FOR PREVIOUS ISSUE
Dim s1 As String = "AAA"
Dim s2 As String = "AAZ"
Dim Last As String = s1.Last
Dim LastS2 As String = s2.Last
Dim StartBase As String = s1.Substring(0, 2)
Dim result As String = String.Empty
For I As Integer = Asc(s1.Last) To Asc(s2.Last)
Dim zz As String = StartBase & Chr(I)
result += zz & vbCrLf
zz = Nothing
MsgBox(result)
Next
**UPDATE CODE VERSION**
Dim BARCODEBASE As String = "SBA0021"
Dim BarCode1 As String = "SBA0021AA1"
Dim BarCode2 As String = "SBA0021CD9"
'return AA1
Dim FirstBarCodeSuffix As String = Replace(BarCode1, BARCODEBASE, "")
'return CD9
Dim SecondBarCodeSuffix As String = Replace(BarCode2, BARCODEBASE, "")
Dim InternalSecondBarCodeSuffix = SecondBarCodeSuffix.Substring(1, 1)
Dim IsTaskCompleted As Boolean = False
For First As Integer = Asc(FirstBarCodeSuffix.First) To Asc(SecondBarCodeSuffix)
If IsTaskCompleted = True Then Exit For
For Second As Integer = Asc(FirstBarCodeSuffix.First) To Asc(InternalSecondBarCodeSuffix)
For Third As Integer = 1 To 9
Dim tmp = Chr(First) & Chr(Second) & Third
Console.WriteLine(BARCODEBASE & tmp)
If tmp = SecondBarCodeSuffix Then
IsTaskCompleted = True
End If
Next
Next
Next
Console.WriteLine("Completed")
Console.Read()
Take a look into this check it and let me know if it can help

Get value of a string that is passed as parameter

I need to pass in parameters to my sub/function.
When the parameter is passed, the value in the string, I would like to get the value evaluated and sent as:
Dim strParams As String = drRow(0)
' drRow is a row from DB Table. the value in drRow(0) =
' "#FromDate=""" & Now.AddDays(-10).ToShortDateString & """&#ToDate=""" & Now.AddDays(-4).ToShortDateString "
I would like to see this converted to:
Dim strFinal as string
strFinal = ProcessString(strParams)
End Result should be:
strFinal = "#FromDate=10/09/2011&#ToDate=10/15/2011"
Any ideas how I can do this. I am getting the initial string from DB, I need to convert to the final string, I am not able to figure out how to write the "ProcessString" function.
Thanks for looking.
"IF" you can change your parameter statement to something simple like:
#FromDate=;-10;#ToDate=;-4
Then you can do something like this:
Dim strParams As String = "#FromDate=;-10;#ToDate=;-4"
Dim value As String = String.Empty
Dim parts() As String = strParams.Split(";"c)
If parts.Length = 4 Then
Dim fromDays As Integer
Dim toDays As Integer
If Integer.TryParse(parts(1), fromDays) AndAlso Integer.TryParse(parts(3), toDays) Then
value = parts(0) + Now.AddDays(fromDays).ToShortDateString + parts(2) + Now.AddDays(toDays).ToShortDateString
End If
End If
MessageBox.Show("Value = " & value)
If it's anything more complicated than that then you will have to start parsing every part of your string with lots of If and Select statements-- you should probably heed Jim Mischel's advice and try a different approach.
This is the end result of what i used based on suggestions.. Thanks Guys.
Public Function ProcessParameters(ByVal strParams As String) As String
Dim arrParams() As String
'strParams = "#FromDate=-10;&#ToDate=-4;&#CompanyID=1"
arrParams = strParams.Split(";")
Dim arrP() As String
Dim strFinalParams As String = ""
For Each strP As String In arrParams
arrP = strP.Split("=")
If arrP(0).ToString.EndsWith("Date") Then
strFinalParams &= arrP(0) & "=" & Now.AddDays(arrP(1)).ToShortDateString
Else
strFinalParams &= arrP(0) & "=" & arrP(1)
End If
Next
Return strFinalParams
End Function
}

Comparing Strings

I would like to compare two strings in a vb.net windows application
Imports System.Windows
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim s As String = "$99"
Dim y As String = "$9899"
If s > y Then
MessageBox.Show("Hi")
End If
End Sub
End Class
Could anyone one correct the logic if there is any mistake in that?
You are comparing strings, not integers.
You could compare them as integers by replacing "$" with "" and then convert it to an integer.
Replace the $ to ""
s = s.Replace("$", "");
y = y.Replace("$", "");
Convert both of them to integers
Dim result1 As Integer
Dim result2 As Integer
result1 = Convert.ToInt32(s)
result2 = Convert.Toint32(y);
Then you can do
if (result1 > result2) { ... }
Dim sum1 As Int32 = 99
Dim sum2 As Int32 = 9899
'this works as expected because you are comparing the two numeric values'
If sum1 > sum1 Then
MessageBox.Show("$" & sum1 & " is greater than $" & sum2)
Else
MessageBox.Show("$" & sum2 & " is greater than $" & sum1)
End If
'if you really want to compare two strings, the result would be different than comparing the numeric values'
'you can work around this by using the same number of digits and filling the numbers with leading zeros'
Dim s As String = ("$" & sum1.ToString("D4")) '$0099'
Dim y As String = ("$" & sum2.ToString("D4")) '$9899'
If s > y Then
MessageBox.Show(s & " is greater than " & y)
Else
MessageBox.Show(y & " is greater than " & s)
End If
I recommend always to use Integers for numeric values, particularly if you want to compare them. You can format the values as string after you compared the numeric values.
What do you mean compare by length or content?
dim result as string
dim s as string = "aaa"
dim y as string = "bbb"
if s.length = y.length then result = "SAME" '= true
if s = y then result = "SAME" '= false
MessageBox.Show(result)