Migration from vba to vb.net - correct logic for using Iserror - vb.net

I'm trying to use this code:
If Not IsError(Convert.ToDateTime(DatiBase(i).innertext.substring(DatiBase(i).innertext.indexof(":") + 1).trim(), New CultureInfo("it-IT"))) Then
MyString = "'" & Convert.ToDateTime(DatiBase(i).innertext.substring(DatiBase(i).innertext.indexof(":") + 1).trim(), New CultureInfo("it-IT")).ToString("yyyy-MM-dd") & "'"
Else
'Do something else
End If
My goal is to assign value to "MyString" only if "Convert.ToDateTime" gives a valid value but the code doesn't do that: It stops when the String isn't recognized as a valid DateTime instead of execute the "else" code.

You should use DateTime.TryParse:
https://msdn.microsoft.com/en-us/library/9h21f14e%28v=vs.110%29.aspx

If you don't know exactly what is the format in which you receive your string then you need to provide a set of possible formats to the DateTime.TryParseExact.
This example below is a simplified test version of your code above
Sub Main
Dim dateConverted as DateTime
Dim testDate = "asdfasldka:08/05/2015 13:10"
Dim yourWannaBeDate = testDate.Substring(testDate.IndexOf(":") + 1).Trim()
Dim possibleFormats = new string() {"d/M/yyyy", "d/M/yyyy H:m", "d/M/yy", "d/M/yy H:m"}
if DateTime.TryParseExact(yourWannaBeDate, possibleFormats, CultureInfo.CurrentCulture, DateTimeStyles.None, dateConverted) then
Console.WriteLine(dateConverted.ToString("yyyy-MM-dd"))
else
Console.WriteLine("Not a date")
End if
End Sub
The above code will match "08/05/2015", "8/5/2015", "08/05/15" and the same strings with the time part in two or one digit format
The trick consists in passing an array of possible formats that could be used to interpret the date in your CurrentCulture (I am assuming that your PC has the culture that match the formats above, however, if this is not the case just initialize a new CultureInfo variable and use it in the TryParseExact)

I wanna thank Leonardo for the tip. This is the code I successfully used:
Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture("it-IT")
Dim DateResult As DateTime
Dim styles As DateTimeStyles = DateTimeStyles.None
Dim mTmpDate As String
mTmpDate = DatiBase(i).innertext.substring(DatiBase(i).innertext.indexof(":") + 1).trim()
If DateTime.TryParse(mTmpDate, culture, styles, DateResult) Then
MyString = "'" & DateResult.ToString("yyyy-MM-dd HH:mm") & "'"
Else
'Do something else
End If
The code works with any kind of date in "italian style" and in "MyString" I get a date/time formatted as mySql needs (for a timestamp field).

Related

vb.net option strict on convert string to date

I am trying to convert a string from a database to a Date type with this format "yyyy-M-d"
The string is stored in this format "yyyy-M-d"
So I can execute this code with the Date variables in this format "yyyy-M-d"
Because Option Strict is ON Visual Studio 2019 ver 16.7.5 is UN-happy
If gvTorF = "False" And varToday > varFTue Then
First I am not sure it is necessary but the posts I read about comparing Dates makes this suggestion
Here are my variables
Dim varToday As Date
Dim varFTue As Date
Dim varStr As String
Next I click a Button to get the data from the Database With this code below
Public Sub GetDateInfo()
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As SQLiteCommand = New SQLiteCommand($"SELECT * FROM DateInfoTable WHERE DID = '1'", conn)
Using rdr As SQLite.SQLiteDataReader = cmd.ExecuteReader
While rdr.Read()
varTorF = rdr("ditORf").ToString
'varFTue = CDate(rdr("diTESTdate")) 'shows as 10/26/2021
'varFTue = Date.ParseExact(varStr, "yyyy-M-d", provider As IFormatProvider, As Date)
'Tried line of code above this can NOT format correct
varTESTdate = CType(rdr("diTESTdate"), String) 'shows as 2021-10-26
End While
rdr.Close()
End Using
End Using
End Using
End Sub
Other than turning Option Strict OFF or just use the format "M-d-yyyy" to run my test
Where varToday > varFTue which seems to work
The Question is what are my other options to make the conversion from String to Date?
The function below will convert the two Strings varTESTdate & varTodayStr
The varTESTdate is from the database and varTodayStr is created in the function bothDates
Here is the Function and the call made behind a Button Click event
bothDates(varTESTdate, varTodayStr)
Public Function bothDates(ByVal varTESTdate As String, ByVal varTodayStr As String) As Object
result1 = Date.ParseExact(varTESTdate, "yyyy-M-d", provider:=Nothing)
Dim dateToday = Date.Today
varTodayStr = dateToday.ToString("yyyy-M-d")
result2 = Date.ParseExact(varTodayStr, "yyyy-M-d", provider:=Nothing)
Return (result1, result2)
End Function
You appear to have the conversion in your code already
Dim d = DateTime.ParseExact("2026-10-26", "yyyy-M-d", Nothing) 'or provide a culture instead of Nothing..
Though I'm not sure what the trailing "As IFormatProvider, As Date" is there for
'varFTue = Date.ParseExact(varStr, "yyyy-M-d", provider As IFormatProvider, As Date)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This is a syntax error in this context in vb, and looks like a remnant artifact of a conversion from C# where we use "as X" to perform casts. Don't assume that converters get all code perfect all the time; you nearly always have to fix up their output, especially if pasting in only parts of a program where they can't see all the declared variables (your code appears to not contain provider as a variable)

Textbox format into Datetime?

I had a problem manipulating the textbox. This is the date format 2019-10-10 05-21-27 and I was about to convert it using datetime. But it seems it cannot be Format like this 2019-10-10 05:21:27 I tried several codes for this one but it did not work.
Here is my code:
Dim d As Date = Date.ParseExact(tbox_dateofS.Text, "d/M", CultureInfo.InvariantCulture)
tbox_dateofS.Text = d.ToString("dd/MM/yy hh:mm:ss")
i tried this one also:
tbox_dateofS.Text = Cdate(node.SelectSingleNode("starttime").InnerText).Tostring("yyyy-mm/dd hh:mm:ss"
And I got this error : System.FormatException: 'String was not recognized as a valid DateTime.'
Of course it can be formatted like that. You simply need to specify the correct format to convert FROM in order to get a Date that you can then format however you want.
Imports System.Globalization
Module Module1
Sub Main()
Dim text = "2019-10-10 05-21-27"
Dim dt As Date
If Date.TryParseExact(text, "yyyy-MM-dd HH-mm-ss", Nothing, DateTimeStyles.None, dt) Then
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"))
Else
Console.WriteLine("Invalid input")
End If
Console.ReadLine()
End Sub
End Module
It works exactly as you should expect.
That said, why use a TextBox in the first place? In most cases, you can use a DateTimePicker and it will handle all the formatting and validation for you.
05-21-27 is a bad format (WITH FORMAT STYLE "d/M") to convert in a time object.
So if you don’t want to change your INPUT format use the method below as a workaround otherwise in order to have a correct date Object you need to change your time input string in 05:21:27 and after to format this date in your style again as you want.
Private Function getFormatedDate(sDate As String, Optional formatString As String = "yyyy-MM-dd HH:mm:ss")
Dim correctDateString As String = ""
For i As Integer = 0 To sDate.Length - 1
If IsNumeric(CChar(sDate(i))) OrElse sDate(i) = " " Then
correctDateString &= sDate(i)
Else
If i < 10 Then
correctDateString &= "/"
Else
correctDateString &= ":"
End If
End If
Next
Return Strings.Format(CDate(correctDateString), formatString)
End Function
Usage:
Dim mCorrectDateString As String = getFormatedDate("2019-10-10 05-21-27")

How to convert time in string format into datetime format in VB.Net

The following string was generated by this code:
myString = 12:44:44.6111472
myString = Date.Now.TimeOfDay.ToString
I want to add 16.1234567 seconds and the value of myString and assign the resulting value to a new string called myNewString.
Every function I have tried looses the 7 decimal places.
Is there another method I can use that doesn't require me to break apart the entire string value, modify the desired parts, account for carry's, then re-assemble?
If not, then so-be-it.
But, I would like think there is some method, and I'm just not finding it!
Thanks!
Datetime has some parsing functions that you can use. For example:
Dim mystring As String = "12:44:44.6111472"
Dim dt As System.DateTime = System.DateTime.Parse(mystring)
dt += New TimeSpan(16.1234567 * TimeSpan.TicksPerSecond)
mystring = dt.TimeOfDay.ToString()
'now mystring = "12:45:00.7346039"
Here's another approach similar to Ben J's without the use of timespan (which may make things look simpler):
Dim myString = Date.Now.TimeOfDay.ToString
' parse datetime string and add seconds
Dim myDate = DateTime.Parse(myString).AddSeconds(16.1234567)
' outputs 16.123000 so you still lose a few decimal points but not all 7,
' is this close enough precision for you?
Dim ts = String.Format("{0:N6}", (New TimeSpan(myDate.Ticks) - New TimeSpan(DateTime.Parse(myString).Ticks)).TotalSeconds)

Formatting String to "dd/MM/yy"

I have a string which needs converting to "dd/MM/yy". I am converting it to a Date datatype and then formatting it back to a string. I was wondering if there is an easier/elegant way of doing it.
Here is an example of how I am achieving this now
Dim strValue As String = "17/08/2016"
Dim dteValue as Date = Convert.ToDateTime(strValue)
strValue = dteValue.ToString("dd/MM/yy")
What I am looking for is a way of converting without casting it to a Date datatype, is it possible?
Without casting it to Date I would suggest:
Dim strValue As String = "17/08/2016"
strValue = strValue.PadLeft(6) & strValue.PadRight(2)
It takes my computer 1 ms to process above code 10.000 times, but 22 ms to process yours.
Edit: if the date has different lengths, you could split on the forwardslash and rebuilt it:
Dim arrSplitValue() As String = Split("17/08/2016", "/")
Dim strValue As String = arrSplitValue(0) & "/" & arrSplitValue(1) & "/" & arrSplitValue(2).PadRight(2)
You could use an extension method:
public static string ToMyDateString(this string stringDate)
{
return DateTime.Parse(stringDate).ToString("dd/MM/yy");
}
And then use it like so:
string strValue = "17/08/2016".ToMyDateString();
or
string strValue = "17/08/2016";
string strValueDate = strValue.ToMyDateString();
Just realised you're in VB.NET so pretty sure it'll translate over. If I get a moment I'll try and do it in VB.NET.
VB.NET version
<System.Runtime.CompilerServices.Extension> _
Public Shared Function ToMyDateString(stringDate As String) As String
Return DateTime.Parse(stringDate).ToString("dd/MM/yy")
End Function
Warning - this has just been put through a converter, so may need to be tweaked.

String.Format for Integer is Incorrect in VB.Net

This should not happen, so I must be missing something simple.
In the below VB function, I am trying to generate a list of part numbers to display on the screen using this format statement:
ticket = String.Format("{0:000}-{1:00000}-{2:00}", storeNumber, order, release)
With that, ticket should have the format xxx-yyyyy-zz so that the ticket is human readable and the other parts of my application can parse this data.
Public Shared Function GetShipTickets(storeNumber As Integer, auditor As String, startDate As DateTime) As ShipTickets
Dim list As New ShipTickets(auditor)
list.Display = String.Format("Since {0:MMMM d}.", startDate)
Const sqlCmd As String =
"SELECT TICKET_STORE, TICKET_ORDER, TICKET_RELEASE " &
"FROM TBLRELHDR " &
"WHERE TICKET_STORE=#TICKET_STORE AND STATUS='C' AND #CREATE_DATE<=CREATE_DATE " &
"ORDER BY TICKET_ORDER, TICKET_RELEASE, CREATE_DATE; "
Dim table As New DataTable()
Using cmd As New DB2Command(sqlCmd, Db2CusDta)
cmd.Parameters.Add("TICKET_STORE", DB2Type.SmallInt).Value = storeNumber
cmd.Parameters.Add("CREATE_DATE", DB2Type.Char, 8).Value = String.Format("{0:yyyyMMdd}", startDate)
table.Load(cmd.ExecuteReader())
End Using
If 0 < table.Rows.Count Then
For Each row As DataRow In table.Rows
Dim order As String = String.Format("{0}", row("TICKET_ORDER")).Trim().ToUpper()
Dim release As String = String.Format("{0}", row("TICKET_RELEASE")).Trim().ToUpper()
Dim ticket As String = String.Format("{0:000}-{1:00000}-{2:00}", storeNumber, order, release)
list.Add(ticket)
Next
End If
list.Sort()
Return list
End Function
It is not working, though.
Also, when I view my data on the screen, it is not displaying correctly either:
What is going on?
VB is not my strongest programming language. Either there is some nuance of VB that I am unaware of or the compiler is messing up.
Using Visual Studio 2012
The format "{2:00}" works on integers, not strings. It won't automatically convert a string consisting of digits into an integer. Manually convert the strings to integers:
Dim ticket As String = String.Format("{0:000}-{1:00000}-{2:00}",
CInt(storeNumber),
CInt(order),
CInt(release))