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
Related
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
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
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.
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.