Can anyone see from the following function why I would be getting an "Invalid Cast Exception"? More specifically this is the error "Conversion from string "yyyyMMdd" to type 'Integer' is not valid."
I am trying to convert a DateTime value from the database to a String with the format "yyyyMMdd" so for example October 22, 1985 would be "19851022".
dbReader(fieldName).ToString("yyyyMMdd")
Here is the entire function ...
Private Function GetDBReaderDateValue(ByVal dbReader As IDataReader, ByVal fieldName As String) As String
If dbReader(fieldName) Is DBNull.Value Then
Return ""
Else
Return dbReader(fieldName).ToString("yyyyMMdd")
End If
End Function
If fieldName is not a DateTime, conversion will fail. Try to cast it to a Datetime first:
Dim dt As Date
If Date.TryParse(dbReader(fieldName).tostring, dt) Then
Return dt.ToString("yyyyMMdd")
Else
Throw New ArgumentException("GetDBReaderDateValue needs a Date-Column as parameter!")
End If
It seems like you're calling ToString on an Object... and there's no overload that takes a String parameter. You probably need to cast to a DateTime first.
Related
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
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
I have one field which is in text format and is used for keeping release date .I have to check whether the date in field is in dd/mm/yyyy format or not.
Please suggest how to do that if the field is in string format.
I would use DateTime.TryParseExact, it will not throw an exeption but will return a bool that represents a valid conversion.
From above link:
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly. The method returns a value that indicates whether the conversion succeeded.
Example:
Dim yourdate As String = "31/12/1999"
Dim mynewDate As DateTime
Dim culture As New CultureInfo("") 'Uses invariant culture
If Not Date.TryParseExact(yourdate, "dd/MM/yyyy", culture, DateTimeStyles.None, mynewDate) Then
MsgBox("Oops")
Else
MsgBox(mynewDate.ToString())
End If
DateTime.ParseExact
trycatch the call since it will throw an exception if it not in the specified format.
format = "d"
dateString = "Sun 15 Jun 2008 8:30 AM -06"
Try
result = Date.ParseExact(dateString, format, provider)
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
Catch e As FormatException
Console.WriteLine("{0} is not in the correct format.", dateString)
End Try
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
I declare my dates as the following in my code:
Dim DeliveryDate as Date
But i am now trying to declare time however i keep getting an error because i cannot get the type correct. I tried the following but get the following error: "Conversion from type 'Timespan' to type 'integer' is not valid".
Dim DeliveryTime as DateTime
Dim DeliveryTime as Integer
In my database the DeliveryTime type is set to Time(7) so i would assume there should be 'Time' which i could use to declare it, but there isnt. What is the correct type i should be using?
Here is my exact code. There error is Input string was not in correct format:
GraphDate4 = String.Empty
DeliveryProducts = "{ name: 'DeliveryProducts', data: ["
If DataReader4.HasRows Then
While DataReader4.Read
Dim DevTime As Timespan = DataReader4("DeliveryTime")
GraphDate4 += """" + DevilTime.ToString("d") + ""","
DeliveryProducts += DataReader4("DeliveryProducts").ToString() + ","
End While
End If
On the client-code side of things (your vb.net code), the Date data type is really an alias for the DateTime data type, which includes a component for both date and time in the same value.
But here, it sounds like maybe you just need a TimeSpan data type, and use TimeSpan's FromSeconds() or FromMilliseconds() methods to construct it.