IsDate is returning unexpected results - vb.net

When I am doing in immediate window
? IsDate("09/01/14")
True
? IsDate("10/23/14")
False
I am not sure why IsDate("10/23/14") is returning false.
any suggestions?
This is my entire function. When I pass 09/01/14 then it doesn't return any error, but when I pass 10/23/14 then it returns error.
Public Shared Sub CheckForDate(ByVal ChkText As String, ByRef ErrorCount As Integer)
Try
ChkText = ChkText.Replace(" ", "").Trim()
Dim dt As DateTime = DateTime.ParseExact(ChkText, "MM/dd/yyyy", Globalization.CultureInfo.InvariantCulture)
If Not IsDate(dt) Then
ErrorCount += 1
End If
Catch
If Len(ChkText) > 0 Then
If Not IsDate(ChkText) Then
ErrorCount += 1
End If
End If
End Try
End Sub
I tried this
? DateTime.TryParse("09/01/14", dt)
True
? DateTime.TryParse("10/23/14", dt)
False

It might be possible that dates in isDate are being processed as dd/mm/yy instead of mm/dd/yy.
Try this code in your application, or be sure your system is processing dates as mm/dd/yy:
Imports System.Globalization
Dim ciNewFormat As New CultureInfo(CultureInfo.CurrentCulture.ToString())
ciNewFormat.DateTimeFormat.ShortDatePattern = "MM/dd/yy"
System.Threading.Thread.CurrentThread.CurrentCulture = ciNewFormat

Use TryParseExact(). This will force you include information indicating the expected format.
As somewhat indicated in comments on this question, the likely problem is that the machine where you are running assumes a DD/MM/YY format instead of your expected MM/DD/YY format.

You must specify a culture that corresponds to date format used:
Public Shared Function IsUSDate(input As String) As Boolean
Dim culture = CultureInfo.CreateSpecificCulture("en-US")
Dim d As DateTime
Return DateTime.TryParse(input, culture, DateTimeStyles.None, d)
End Function

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

Conversion from string "M" to type 'Integer' is not valid

I am having an issues with conversion of values that I am trying to reference via a field that I want to format from an ERP System. I am unable to convert all of my values because they are being pulled out as strings, no matter if variables are set to integer or string. What am I doing that would cause this error, should variables be defined a different way?
Public Class Class1
Inherits erp.Rule
Public Overrides Function Execute() As erp.RuleResult
Dim Result As New RuleResult
Try
Dim date_recieved As Date
Dim month As String
Dim period As String
Dim Year1 As String
Dim Year As String
date_recieved = Data.Fields.GetFieldByAlias("date_received").FieldValue
month = Format(date_recieved, "M").ToString
Year = Data.Fields.GetFieldByAlias("yearAR").FieldValue
period = Data.Fields.GetFieldByAlias("periodAR").FieldValue
If period = month Then
If Year = Year1 Then
Exit Function
Else
MessageBox.Show("Date received does not match year", "Invalid Input")
End If
Else
MessageBox.Show("Date received does not match period", "Invalid Input")
End If
Catch ex As Exception
Result.Message = ex.Message
End Try
Result.Success = True
Return Result
End Function
Format does not accept a string parameter, by you passing "M" it is trying to convert the datatype you supply to the datatype the function accepts and since a string does not implicitly cast to an integer an error occurs
To format a Date type to various formats of string you just use your date variable and its subsequent .ToString() method with your formatting rules as an argument of .ToString()
Here is a link to the msdn explaining all the possible formatting options: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

VB .NET comparing strings

I don't get what's going on. The method equals doesn't work, and neither comparing the strings with the '=' operator or with 'string.compare'. thetruth is always set as "false".
Public Function ProcessLabel(myValue As Object) As String
If ((myValue Is DBNull.Value) = False) Then
Dim thetruth As Boolean
Dim myValueStr As String
myValueStr = CStr(myValue)
thetruth = String.Equals(myValueStr, "01/01/1900")
End If
Return myValue.ToString
End Function
I cannot attach images but I assure you, in myValueStr I have "01/01/1900".
I'm pretty sure that myValue is a Date object and not a string and that a database is involved where the minimum value is 01/01/1900, for example the SMALLDATETIME datatype. If you look at it in debugger you see it like 01/01/1900. But if you execute ToString( internally used on CStr(myValue)) you get the localized representation including the time portion, so something like 01.01.1900 00:00:00 (f.e. in germany).
Instead compare the right types:
If Not myValue Is DBNull.Value AndAlso Not myValue Is Nothing Then
Dim date = DirectCast(myValue, Date)
If date = New Date(1900, 01, 01) Then
End If
End If

Validate the date format in vb.net

I have the grid cell value to validate for a correct format as below
Date value should be in DD-MON-YYYY format and for this i am using below validation
Public Function ValidateDateForError(ByVal checkInputValue As String) As Boolean
Dim returnError As Boolean
Dim dateVal As DateTime
If Date.TryParseExact(checkInputValue, "DD-MON-YYYY",
System.Globalization.CultureInfo.CurrentCulture,
DateTimeStyles.None, dateVal) Then
returnError = True
Else
MessageBox.Show("not converted")
End If
Return returnError
End Function`
DateTime value should be in DD-MON-YYYY HH:MI:SS format and for this i am using below validation
Public Function ValidateDateTimeForError(ByVal checkInputValue As String) As Boolean
Dim returnError As Boolean
Dim dateVal As DateTime
If DateTime.TryParseExact(checkInputValue, "DD-MON-YYYY HH:MI:SS",
System.Globalization.CultureInfo.CurrentCulture,
DateTimeStyles.None, dateVal) Then
returnError = True
End If
Return returnError
End Function`
EDate (valid European date) value should be in DD/MM/YY format and for this i am using below validation
Public Function ValidateEDateForError(ByVal checkInputValue As String) As Boolean
Dim returnError As Boolean
Dim dateVal As Date
If Date.TryParseExact(checkInputValue, "DD/MM/YY",
System.Globalization.CultureInfo.CurrentCulture,
DateTimeStyles.None, dateVal) Then
returnError = True
End If
Return returnError
End Function`
JDate (valid Julian date) value should be in MM/DD/YY format and for this i am using below validation
Public Function ValidateJDateForError(ByVal checkInputValue As String) As Boolean
Dim returnError As Boolean
Dim dateVal As Date
If Date.TryParseExact(checkInputValue, "MM/DD/YY",
System.Globalization.CultureInfo.CurrentCulture,
DateTimeStyles.None, dateVal) Then
returnError = True
End If
Return returnError
End Function`
but none of above is working. could anyone tell me where i am making mistake?
Thanks in Advance.
Using ParseExact means that you will be telling it the precise format the string will be in. These are case sensitive to allow things like H vs h for 12/24 clock and MM vs mm to distinguish Month from Minutes. So, "DD-MON-YYYY" is invalid, "dd-MM-yyyy" may be what you are after.
But, this means the user would always have to enter 2 digits for the day and month as in "19-07-2014" or "04-07-2014" which they are often not inclined to do, and seems harsh to impose. TryParseExact will take an array of formats so you can be flexible:
Dim strFoo As String = "19-7-2014" ' d-MM-yyyy
Dim strBar As String = "19-07-2014" ' dd-MM-yyyy
Dim strJuly4 As String = "4-7-2014" ' d-M-yyyy
' several possible format styles
Dim formats() As String = {"d-MM-yyyy", "dd-MM-yyyy",
"dd-M-yyyy", "d-M-yyyy"}
Dim thisDt As DateTime
' this should work with all 3 strings above
If DateTime.TryParseExact(strFoo, formats,
Globalization.CultureInfo.InvariantCulture,
DateTimeStyles.None, thisDt) Then
Console.WriteLine("Success! {0}", thisDt.ToString)
End If
Most of the time there it is silly to force them to enter "04" for a month or day and d/M/yyyy will work with strings with the leading "0" (but not the reverse!). Its is added here mainly to show how to pass an array of format patterns.
DO consult MSDN for the proper Standard Date and Time Format Strings
As for Julian Dates, one form of them is to use the form yyDDD to denote the 2 digit year and day of year for the last 3 digits. I dont know if the convention for this changed after 1/1/2000 when all Julian for this Century would sort below those for the 1990s. Still, here is how it is done:
Dim jdt As DateTime = #2/11/2010#
Dim jdate As String = xdt.Year.ToString & xdt.DayOfYear.ToString("000")
' ===> '2010042 or 42nd day of 2010
jdate = (xdt.Year - 2000).ToString("00") & xdt.DayOfYear.ToString("000")
' ===> '10042 or 42nd day of 2010

VB Function to return records based on a date parameter & date field OR another date field (Visual Studio 2008, Report Builder 3.0, SharePoint Lists)

Another question sourced from this tricky environment and my inexperience. It seems like VB Functions are the only way I can deliver on some of these report requirements.
I have a situation where a user wants to see data in a report as follows:
The general requirement is this: when the report is initialized, no data is shown - the user must put in a parameter. This is complete. The parameter is a date parameter - if the date is blank, all items in the list will be returned. If a date is entered for the parameter, all items of typeA or typeB equal to or greater than the data param must be returned.
More specifically, this is what I am trying to accomplish:
Return all items where typeA_date is not blank and is greater than or equal to the date entered in the parameter OR return all items where typeB_date is not blank and is greater than or equal to the date entered in the parameter.
Here is the code I have, but it is returning an error:
Function dtComprRtrn(ByVal awardField As String, ByVal suspendField As String, ByVal chkDtField As String) As Boolean
If chkDtField Is Nothing Then
Return True
End If
Dim awardDate As Date
Dim suspendDate As Date
If (IsDate(awardDate)) Then
chkDtField = Convert.ToDateTime(awardDate)
ElseIf (IsDate(suspendDate)) Then
chkDtField = Convert.ToDateTime(suspendDate)
Else
Return False
End If
If awardDate >= chkDtField Then
Return True
Else
If suspendDate >= chkDtField Then
Return True
Else
Return False
End If
End If
The error is this:
"An unexpected error occurred while compiling expressions. Native
compiler return value: ‘[BC30289] Statement cannot appear within a
method body. End of method assumed"
I don't have much experience in this area, or in integrating a function into Report Builder, and I am eternally grateful for any assistance that may be provided. Thank you much!
Here is the final code solution that was implemented and appears to be working:
Function dtComprRtrn(ByVal awardField As String, ByVal suspendField As String, ByVal chkDtField As String) As Boolean
If chkDtField Is Nothing Then
Return True
End If
Dim compareDate As Date = DateTime.MinValue
Dim chkDtDate As Date = DateTime.MinValue
' Check to see if input string chkDtField is a date
If (IsDate(chkDtField)) Then
chkDtDate = Convert.ToDateTime(chkDtField)
End If
' Check to see if either awardField or suspendField is a date
' if not then return false
If (IsDate(awardField)) Then
compareDate = Convert.ToDateTime(awardField)
ElseIf (IsDate(suspendField)) Then
compareDate = Convert.ToDateTime(suspendField)
Else
Return False
End If
' Now we know we have a date in compareDate
' and we know that chkDtDate is at least DateTime.MinValue
' so if chkFtField was blank then this comparison will always
' work if we have a valid date for awardField or suspendField
If compareDate >= chkDtDate Then
Return True
Else
Return False
End If
End Function