Convert value from string to date format in SQL Server 2008 - vb.net

I want to convert date which is stored as string in a SQL Server 2008 database to smalldatetime.
The format for the saved string is 16/12/2007 and I want to remove / and replace it with - to get proper date format which is 16-12-2007
I getting the following error
Conversion from string "16/12/2007" to type 'Date' is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Conversion from string "16/12/2007" to type 'Date' is not valid.
Source Error:
Line 34: NewsItem.Visible = True
Line 35: NewsItem.Date_Modified = CDate(GetContent.Ndate)
Line 36: NewsItem.Date_Published = CDate(GetContent.Ndate)
I thought of creating a function that replace the / character with - to then update the database but it will take long time.

Don't use strings if you actually want to store datetime/smalldatetimes. Use sql-parameters to avoid localization/format issues and - more important - to prevent sql-injection. A VB.NET Date can be used for a smalldatetime column. Use Date.TryParse to validate and parse the string.
Dim sql = "INSERT INTO dbo.TableName(Date_Modified)VALUES(#Date_Modified);SELECT CAST(SCOPE_IDENTITY() AS INT);"
Using con = New SqlConnection("Connection-String")
Using cmd = New SqlCommand(sql, con)
Dim dt As Date
If Not Date.TryParse(GetContent.Ndate, dt) Then
MessageBox.Show("please enter a valid date")
Return
End If
cmd.Parameters.AddWithValue("#Date_Modified", dt)
Dim newID = cmd.ExecuteScalar() ' presuming that you have an identity column that is autoincremented
End Using
End Using

Retrieve the date as string from database and then use Date.ParseExact which Converts the specified string representation of a date and time to its DateTime equivalent.
Dim ydate = "16/12/2007"
Dim edate As Date = Date.ParseExact(ydate, "dd/MM/yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo)

Related

Retrieving "Number" From Sql VB.NET System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression.'

If I want to retrieve a value that is saved as a number in an access database.
Im using the following:
Dim sql As String = "SELECT ArithmeticScore FROM " & tablename & " WHERE DateAscending = '" & todaysdate & "'"
Using connection As New OleDbConnection(getconn)
Using command As New OleDbCommand(sql, connection)
connection.Open()
scorevalue = CDec(command.ExecuteScalar()) 'Data type mismatch in criteria expression.
connection.Close()
End Using
End Using
MsgBox(scorevalue)
getconn = connection string as a string
scorevalue = Nothing as decimal
The field ArithmeticScore is set to Number in the table.
The exact value in the cell right now is 50, but the program should allow for any decimal value.
The error im getting is "Data type mismatch in criteria expression".
The criteria expression mentioned in the error message does not refer to the ArithmeticScore output. It's talking about the WHERE clause. Whatever you have for todaysdate does not match what the database is expecting for the DateAscending column.
Since OleDb is a generic provider, we don't know exactly what kind of database you're talking to, but most databases have a way to get the current date value in SQL: getdate(), current_timestamp, etc. Using that mechanism will likely solve the conflict, and there's no need to use string concatenation for this in the first place.
Dim sql As String = "SELECT ArithmeticScore FROM " & tablename & " WHERE DateAscending = Date()"
The other way you can fix this is with proper parameterized queries, which you should doing anyway. It's NEVER okay to use string concatenation to substitute data into an SQL query, and if you find yourself needing to think about how to format a date or number string for use in an SQL command, you're almost always doing something very wrong.

VB.NET date format

How do I replace 2014-12-27 with the current date in the statement
Dim cmd As New SqlCommand("Select * from LateComersReport where PDate = '2014-12-27'", conn)
or how can I have the date in the format 'yyyy-mm-dd'in the statement
Dim Tday As Date = Date.Today
First, a date has no format, it has only a value. A date-string can have a format.
Second, always use sql-parameters instead of string concatenation if you build your sql query. That prevents sql-injection or conversion/locatization issues. And always pass the correct type(date is this case) instead of letting the database interpret your argument.
Using cmd As New SqlCommand("Select * from LateComersReport where PDate = #PDate", conn)
cmd.Parameters.Add("#PDate" , SqlDbType.Date).Value = Date.Today ' or SqlDbType.DateTime '
' .. '
End Using
You can simply change your SQL query to this:
"Select * from LateComersReport where PDate = CONVERT(DATE, GETDATE())"
A few things I'd like to point out: date variables, whether in SQL or in .NET, do not have formats. Formatting is only useful/relevant when you are talking about displaying a date, i.e. as a string in a report or in a UI. You shouldn't care how a date is displayed when it's a date value being used in your code.
Also, as a habit, you should use parameters in your SQL statements whenever applicable as opposed to concatenating strings together. For example, if you were to insert your own date value in the query instead of using SQL's built-in GETDATE() function, you would do this:
Dim cmd As New SqlCommand("Select * from LateComersReport where PDate = #MyDateValue", conn)
Dim param As New SqlParameter("#MyDateValue", Now)
cmd.Parameters.Add(param)
The reason for this is string concatenation to build SQL is inherently unsafe due to the risk of SQL injection attacks.

vb.net System.IFormatProvider runtime error

I have this function in vb.net:
Function GetFirstDayOfMonth(ByVal dtDate As DateTime) As DateTime
Dim dtFrom As DateTime = dtDate
dtFrom = dtFrom.AddDays(-(dtFrom.Day - 1))
Return dtFrom
End Function
I am then calling it here:
GetFirstDayOfMonth(reader3.GetString(3).ToString("yyyy-MM-dd"))
I have checked the value of reader3.GetString(3) using a MsgBox and it equals
2015-02-23
But i am getting a runtime error saying:
Additional information: Unable to cast object of type 'System.String' to type 'System.IFormatProvider'.
You're passing a string value into a function that requires a DateTime.
Dim tmp as DateTime
' Don't use the string format here. If it's already
' a string - GetString - then it doesn't need a date format
' I recommend listening to #Hans Passant and #Bjørn-RogerKringsjå
' If your data is already a date, use the date functions to
' keep it as a date
Dim tmpStr As String = reader3.GetString(3)
If DateTime.TryParse(tmpStr, tmp) Then
GetFirstDayOfMonth(tmp)
End If
To keep it as a date without ever casting or formatting it (assuming it's a date object in the database)
Dim firstDay As DateTime = GetFirstDayOfMonth(reader3.GetDateTime(3))
Additionally, turning option strict on should turn this into a compile time error (much more useful).

Trouble converting DateTime (.net) to datetime (SQL server)

I'm trying to pass a string (from a text file) - '17/07/99' into a sql server table - the destination is a date column.
the insert is in a string, of the form:
Dim cmd As New SqlCommand(...yada...)
cmd.CommandText = "INSERT INTO my.table (thisDate, ...etc... ) VALUES (#myDate, ...etc...)"
I am adding the parameters to the cmd using:
cmd.Parameters.Add("#myDate", SqlDbType.DateTime).Value = Date.ParseExact("11/11/11", "dd/MM/yy", CultureInfo("en-GB"))
When I come to ExecuteNonQuery
I get cannot convert string to datetime error.
I thought the ParseExact was doing the conversion from string to DateTime??
Do I really need to do a CONVERT in the sql as well as using datetime structures ?!
Try this:
cmd.Parameters.Add("#myDate", SqlDbType.DateTime).Value = new DateTime(2011, 11, 11);
And also see this:
http://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx
just tested this and it works ... you only need to format your date if you want it consistent no matter what culture your OS is otherwise you don't have to do that
you can use this way
Dim d As Date = "17/07/99"
or you can use this way
Dim d As Date = "17.07.99"
if you only have date without time then it doesn't matter what you use
you can either use this
cmd.Parameters.Add("#myDate", SqlDbType.DateTime).Value = d
or this
cmd.Parameters.Add("#myDate", SqlDbType.Date).Value = d
i just tried both versions mixed and no error whatsoever and rows inserted
Try formatting the string before adding it.
Format(YourTimeStringHere, dd-MM-yy)

sql from vb cannot convert to date

Hi i'm trying to convert this line to get list of people active over todays date but cannot get it to work
adapter.SelectCommand = New SqlCommand( _
"select * from klijent where convert(varchar,convert(datetime,replace('" & DateTimeUgovora.Value.ToString & "','#','')),111) >= convert(varchar,getdate(),111)", myConn)
error is conversion of varchar data type to a datetime data type resulted in an out-of-range value.
my string that I get from front is
"29.11.2013. 19:41:08"
I searched everywhere and cannot find the answer please help
You should not need to convert the datetime value to a string, because in SQL you can compare datetime values directly. This is much more stable as it doesn't depend on locale settings. I don't fully understand your SELECT clause as even if the comparison works, it will return either all the rows in the table or none.
However, if you want to use the table column Kli_Ugovor_do in your comparison, you can change your statement to this:
adapter.SelectCommand = New SqlCommand( _
"select * from klijent where Kli_Ugovor_do >= getdate()", myConn)
Btw: in your statement you included the value of the combobox by string concatenation. You should get used to including parameters in your statements in order to avoid SQL injection attacks.
So if you want to use the value of the DateTimePicker, your code should look similar to this:
adapter.SelectCommand = New SqlCommand( _
"select * from klijent where Kli_Ugovor_do >= #dt", myConn)
adapter.SelectCommand.Parameters.AddWithValue("#dt", dateTimeUgovora.Value)
I just created a quick console application with the string mention by you. This may be helpful.
Imports System.Globalization
Module Module1
Sub Main()
Dim myDateString As String = "29.11.2013. 19:41:08"
myDateString = myDateString.Replace(".", "")
Dim myDate As DateTime = DateTime.ParseExact(myDateString, "ddMMyyyy HH:mm:ss", CultureInfo.InvariantCulture)
Console.WriteLine(myDate.ToString())
Console.ReadLine()
End Sub
End Module
I created a quick module for tsql as well, maybe it will help:
Declare #dt varchar(20)
set #dt = '29.11.2013. 19:41:08'
select convert(datetime, Replace(#dt, '. ', ' '), 103)