DateTime.TryParse fails for perfectly valid dates - vb.net

I've read this string from a file: 23/07/1998. This is a perfectly valid date string. It has no ambiguity, given those numbers there (appears) to be only one possible way to parse it.
DateTime.TryParse, on the other hand, tells me its invalid. I suspect this is due to my culture settings.
TryParse has variations that are rather complex, so I'm wondering if there's an easy way to parse this with "dd/MM/yyyy"?

TryParse doesn't know if your date is MM/dd/yyyy or dd/MM/yyyy. It's obvious to the observer only because we can deduce from the fact that there is no month 23. But it wouldn't know what 02/03/1998 was.
DateTime.ParseExact(dateString, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)
Will tell it which format to use.

Dim iString As String = "01/12/1998"
Dim oDate As DateTime = DateTime.ParseExact(iString, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)
MsgBox(oDate.ToString())

Like already mentioned by dwilliss the regular DateTime.TryParse() method cannot distinguish between dd/MM and MM/dd, and operates only on a standard set of date time formats. To specify a different format use either DateTime.ParseExact() or DateTime.TryParseExact()
If you want a less annoying syntax you can create an extension method wrapping the DateTime.TryParseExact() method.
Imports System.Globalization
Imports System.Runtime.CompilerServices
Public Module Extensions
<Extension()> _
Public Function TryParseDate(ByVal Input As String, ByVal Format As String, <Out()> ByRef Result As DateTime) As Boolean
Return DateTime.TryParseExact(Input, Format, CultureInfo.InvariantCulture, DateTimeStyles.None, Result)
End Function
End Module
Now you can use it like this:
Dim DateString As String = "23/07/1998"
Dim ResultDate As DateTime = Nothing
If DateString.TryParseDate("dd/MM/yyyy", ResultDate) Then
MessageBox.Show("Success: " & ResultDate.ToString())
Else
MessageBox.Show("Input was not a valid date!")
End If

Related

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

datetime variable with extra hour and custom format as datetime not string

This is so simple but i am not able to figure out how to do it, please excuse my ignorance.
I would like a datetime variable to be current datetime + 1 hour in the format "yyyy-mm-dd HH:mm:ss"
I have tried this so far (dotnetfiddle.net) and when i assign it to the datetime variable the date is changed to slashes instead of hypen.
Imports System
Public Module Module1
Public Sub Main()
Dim tet As String = Datetime.Now.AddHours(1).ToString("yyyy'-'MM'-'dd hh:mm:ss")
Dim expiryTime As DateTime = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
System.Globalization.CultureInfo.InvariantCulture)
Console.WriteLine(convert.todatetime(tet))
Console.WriteLine(tet)
Console.WriteLine(Datetime.Now.AddHours(1))
End Sub
End Module
As per one of the comments I have used parseExact and i still see the date with slashes instead of hypen
When you convert tet back to a DateTime it will display as the default pattern. Keep it as a string for display. The convert it back with ParseExact when you need to use it as DateTime again.
Dim dNow As DateTime = DateTime.Now.AddHours(1)
Dim strNow As String = dNow.ToString("yyyy-MM-dd hh:mm:ss")
Console.WriteLine(strNow)

BC42322 VB.NET Runtime errors might occur when converting 'String' to 'IFormatProvider'

I'm trying to migrate old VB6(Visual Basic 6.0) Project to VB.net framework 4.6x.
But I had to move to .net framework 2.0 first.
I used to convert numbers in TextBox to formatted numbers using ToString as below.
In Visual Studio 2017 .net framework 2.0, I have BC42322 warning.
Is there a way to solve this?
txtDividend.Text = txtDividend.Text.ToString("###,###,##0")
I also have
On Error GoTo Error_Handle
at the start of the function to handle characters in that textbox
The Text property is already a string, and the ToString() method for string doesn't have the overload you want.
Since it seems this same text field can hold both the formatted and unformatted version of a value, what you may want to do is first strip off any formatting, convert to a numeric type like Integer or Decimal, and then use the ToString() method from there:
Public Function FormatDividend(dividend As String) As String
Dim extraCharacters As New Regex("[^\d,.-]")
dividend = extraCharacters.Replace(dividend, "")
Return FormatDividend(CDec(dividend))
End Function
Public Function FormatDividend(dividend As Decimal) As String
Return Dividend.ToString("###,###,##0")
End Function
You can call those functions like this:
txtDividend.Text = FormatDividend(txtDividend.Text)
And of course you can tweak that expression however you want, or change the overload and cast to use Integer instead of Decimal.
Since you are trying to migrate from an environment where "1000".ToString("###,##0") produced 1,000, you will want that to work in your new (.net). That solution is to create an extension method that essentially provides the overload.
<Extension>
Function ToString(input as String, format as String) as String
Static numericOnly As Regex = New Regex("[^\d.-]")
Dim asDec as Decimal
Decimal.TryParse(numericOnly.Replace(input, ""), asDec)
Return asDec.ToString(format)
End Function
Since I have more than one TextBox to use format, I upgraded Joel Coehoorn's answer to use format TextBox in my project.
First, I created CommonFunction.vb module file
Imports System.Text.RegularExpressions
Module CommonFunction
Public Function FormatNumberInText(text As String, format As String) As String
Dim extraCharacters As New Regex("[^\d,.-]")
text = extraCharacters.Replace(text, "")
Return FormatNumberInText(CDec(text), format)
End Function
Public Function FormatNumberInText(text As Decimal, format As String) As String
Return text.ToString(format)
End Function
End Module
and in my TextBox vb file, I used it as below.
txtDividend.Text = FormatNumberInText(txtDividend.Text, "###,###,##0")
txtDividendRatio.Text = FormatNumberInText(txtDividendRatio.Text, "###,###,##0.0#")
Thank you Joel Coehoorn.
It appears that the ToString() Method is designed to convert other types to a string and format them as desired. It was not designed to format an existing string. The simplest way I have found around this problem is to convert your string into another data type and then apply the ToString() Method.
So in your case I would convert to a double using the CDbl() Method:
txtDividend.Text = CDbl(txtDividend.Text).ToString("###,###,##0")

SQL datetime to string format

I have some code which declares an object variable, and this variable is assigned a value from an existing database field.
Dim datestart As Object
datestart = dbToDate(dr("DateStart"))
The variable is then passed through a function which checks whether or not it is null, and then converts it into datetime data type.
Public Shared Function dbToDate(o As Object) As DateTime
If o Is DBNull.Value Then
Return Nothing
Else
Return Convert.ToDateTime(o)
End If
End Function
The last thing I need to do with it is convert it into a date formatted string, DD/MM/YYYY, so that I can insert it into a new database.
The function that I have so far is
Public Shared Function sqlDate(dt As DateTime) As String
Return "'" & Format(dt, "yyyyMMdd") & "'"
End Function
However, when I run the code, I get the following error message
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Why is this, and how do I fix it?
Simply, you can use toString function. Also check your timezone. The problem might be in the time zone setting.
Hope you are passing date as string to database, Try to pass date as Datetime variable rather than string
Public Shared Function sqlDate(dt As DateTime) As String
Return dt.toString("yyyy-MM-dd")
End Function
For your Ref: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Error converting string to Custom Date Format

In my application I got error when trying to convert a Date from string date format as shown below:
dateFormat = Format(CDate("2014-mar-06"), "MM/dd/yyyy")
Error
Conversion from string "2014-mar-06" to type 'Date' is not valid
This problem only comes when my Region and Language setting is Spanish(Mexico) (or any spanish but not for others) in Windows 7 . What is the problem and how to solve this?
Avoid VB6 functions like CType and use .NET methods like TryParse instead.
Also CultureInfo.InvariantCulture gets the CultureInfo object that is culture-independent (invariant)
Try this
Dim dateString = "2014-mar-06"
Dim dateValue As DateTime
If DateTime.TryParseExact(dateString, _
"yyyy-MMM-dd", CultureInfo.InvariantCulture, _
DateTimeStyles.None, dateValue) Then
Dim myDate = dateValue.ToString("MM/dd/yyyy") 'Your Date is stored in myDate
Else
'Unable to parse your dateString
End If