Dealing with dates in dd/mm/yyyy format - sql

I have a VB6 application which works with datetime values in SQL Server (which are obviously storing dates as mm/dd/yyyy).
I need to represent these dates to the user as dd/mm/yyyy, read them in as dd/mm/yyyy, and then store them back into the database as the standard mm/dd/yyyy.
This is the current code snippets I have which pull + insert the dates, however I have read many conflicting methods of handling the conversions, and I was wondering if anyone here knew a clear solution for this situation.
"SELECT * FROM List WHERE DateIn LIKE '%" & txtDateIn.Text & "%'"
"UPDATE [Progress] SET [Date] = '" & txtDate.Text & "'"
txtDate.Text = "" & RecordSet.Fields("Date").Value
Any thoughts? Thanks in advance.
**Update
Actually I just noticed I do have dates stored in datetime fields in the form of 16/08/2009 00:00:00 which is dd/mm/yyyy. So perhaps I misunderstood the problem. But when trying to update the datetime value I have been getting 'The conversion of char data type to a datetime data type resulted in an out-of-range datetime value.'.
I assumed this was because the date formats did not match (causing a problem with having a month value out of range) however I do have date values in the format of day/month/year in the datetime field already. And the date being submitted to the database is definitely dd/mm/yyyy.
**** Update 2**
Ok, there seems to be some confusion I have caused. I apologize.
I am storing the dates as datetime in the SQL database
The texts are TextBox controls in the VB6 application
I am running SQL SELECT statements to read the dates from the database and place the value in a TextBox
I then have a 'commit' command button which then performs an UPDATE SQL statement to place the value of the TextBox into the datetime field in the SQL database
This works perfectly fine until 1 specific occasion.
In this occasion I have a datetime value (which SQL Server 2005 displays as 16/08/2009 00:00:00) which is read from the database and populated the TextBox with the value 16/08/2009. Now when I try to run the UPDATE statement without modifying the TextBox text I get the error 'The conversion of char data type to a datetime data type resulted in an out-of-range datetime value.'
This does not occur with other records such as one where the date is 04/08/2009 so the only issue I can see is possibly with the position of day and month in the value because if the DB is expecting month first then obviously 16/08/2009 would be out-of-range. However the value in the database is already 16/08/2009 with no issues.

SQL Server doesn't "obviously" store dates as mm/dd/yyyy. It doesn't store them in a text format at all, as far as I'm aware.
I don't know what the VB6 support for parameterised queries is, but that's what you want: basically you want to pass the argument to the query as a date rather than as text. Basically you should parse the user input into a date (in whatever way VB6 does this) and then pass it through in the paramterised query.
EDIT: I've tried to find out how VB6 handles parameterised queries, and not had a great deal of luck - hopefully any good book on VB6 will cover it. (There are loads of examples for VB.NET, of course...) There's a Wrox post which gives an example; that may be enough to get you going.
EDIT: As the comment to this answer and the edit to this question edit indicate, there's some confusion as to what your data types really are. Please don't use character-based fields to store dates: no good can come of that. Use a proper date/datetime/whatever field, and then make sure you use parameterised queries to access the database so that the driver can do any necessary conversions. Relying on a text format at all is a bad idea.

Use the ODBC Canonical form of the date or timestamp in your queries.
This avoids any misunderstanding due to localization when storing the dates.
The timestamp format is {ts 'yyyy-mm-dd hh:mm:ss[.fff]'}
The date format is {d 'yyyy-mm-dd'}
Here are the functions I use for this.
Now as for entry and display in VB6. Ideally you'd be using the datetimepicker control instead of a textbox as that returns a date and there is no misunderstanding when using it which date you are picking. But if you can assume it is always DD/MM/YYYY (that is a big if), you can use Format(datevalue, "DD/MM/YYYY") to display it. To read it into a date variable you can't just use CDate. You'll need to use parsing and something like DateSerial to put it together: DateSerial(Right(strDate, 4), Mid(strDate, 4, 2), Mid(strDate, 1, 2)).
' ------------------------------------------------------------------------------
' DateLiteral
'
' Description :
' given a vb date, it returns a string with the odbc canonical date format.
'
' History
' 2008-02-04 - WSR : added to this project
'
Public Function DateLiteral(ByRef dtSource As Date) As String
DateLiteral = _
"{d '" & LeftPadDigits(Year(dtSource), 4) & "-" & _
LeftPadDigits(Month(dtSource), 2) & "-" & _
LeftPadDigits(Day(dtSource), 2) & "'}"
End Function
' ------------------------------------------------------------------------------
' ------------------------------------------------------------------------------
' TimeStampLiteral
'
' Description :
' given a vb date, it returns a string with the odbc canonical timestamp format.
'
' History
' 2008-02-04 - WSR : added to this project
'
Public Function TimeStampLiteral(ByRef dtSource As Date) As String
TimeStampLiteral = _
"{ts '" & LeftPadDigits(Year(dtSource), 4) & "-" & _
LeftPadDigits(Month(dtSource), 2) & "-" & _
LeftPadDigits(Day(dtSource), 2) & " " & _
LeftPadDigits(Hour(dtSource), 2) & ":" & _
LeftPadDigits(Minute(dtSource), 2) & ":" & _
LeftPadDigits(Second(dtSource), 2) & "'}"
End Function
' ------------------------------------------------------------------------------
' ------------------------------------------------------------------------------
' LeftPadDigits
'
' Description : pads the given string to the left with zeroes if it is under
' the given length so that it is at least as long as the given length.
'
' History
' 2008-02-04 - WSR : added to this project
'
Public Function LeftPadDigits(ByVal strSource As String, ByVal lngLength As Long) As String
If Len(strSource) < lngLength Then
LeftPadDigits = String$(lngLength - Len(strSource), "0") & strSource
Else
LeftPadDigits = strSource
End If
End Function
' ------------------------------------------------------------------------------
Also should be noted, yes the first choice is to use ADO and parameterized queries.
In my case I access the database through a third party library and can't use parameterized queries. Thus the date literal handling. Here is an example of the ADO parameterized queries though. The code can be different depending on which type of ADO connection you are using though: OLEDB, ODBC or SQLNative. Sometimes it isn't just a ? for the parameter marker. This example is OLEDB.
Set cmdVerifyUser = New ADODB.Command
cmdVerifyUser.CommandType = adCmdText
cmdVerifyUser.CommandTimeout = 30
cmdVerifyUser.CommandText = "SELECT username FROM users WHERE userid = ?"
cmdVerifyUser.Parameters.Append cmdVerifyUser.CreateParameter("userid", adVarChar, adParamInput, Len(m_strUserName), m_strUserName)
cmdVerifyUser.ActiveConnection = m_conDatabase
Set rstResults = cmdVerifyUser.Execute()
If Not rstResults.EOF Then

Well after all of that the problem was simple. I have the date value wrapped in single (') and double (") quotes. The problem was encountered due to date values not requiring the single quotes. Removing them solved the issue.
Thank you anyway for trying to help all.

Related

String to date error (Conversion from string to type date is not valid)

I want to crate date as MS Access like date (example -> #mm/dd/yyy#) input date can be string or date so I have created object variable to hold value of date. Then I convert it to msaccess date.
but it gives error. See the picture attached.
Before posting this question I had searched a lot, but I don't understand the solutions I found.
A major solution is ParseExact("Date String", "Format", System. IFormatProvider). But in my editor Intellisense does not recognize culturevalue. It tells me culturevalue is not defined.
Then I tried Date.tryparse(). It worked, but if I have to use this, then what is use of CDate conversion function?
Edit 1 :
Date.tryparse() does not work it returns false
in vb6
"#" & Month(dateIn) & "/" & Day(dateIn) & "/" & Year(dateIn) & "#"
works perfectly
It seems that you ask for a string expression for a VBA date value.
That can be done like this:
Dim DateIn As DateTime
DateIn = DateTime.Today
Dim Rval As String
Rval = DateIn.ToString("'#'MM'/'dd'/'yyyy'#'")
Console.WriteLine(Rval)
' Output:
' #07/10/2022#

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.

SQL: Compare Date Range in a String text field

I have an MS Access db. I am writing an application in C# to access it. I have a field "FileName" of type "Short Text in MS Access. Data in FileName field is like "Test 11-12-2004 15.11.15".
Using a Date Range, I got to search records based on FileName field. I am not able to get - How do I compare the date of this format and retrieve the records ? FileName is a Text type and date is a substring of it. Retrieving only the date part and comparing with >= beginDate && <= endDate seems like a puzzle to me.
Can anyone suggest how do I write SQL query to perform this date range comparision and retrieve those records - "Select * from TestHead where FileName......" ????
Any help is appreciated.
Thanks a lot,
In your C# code, as you are going through the records, I'd split the string like this:
char[] delimiters = {' '};
string[] FileNameParts = FileName.Split(delimiters);
This will result in an array FileNameParts, the second element of which will contain the date, which you can convert to an actual date for use in the query:
DateTime FileNameDate = Convert.ToDateTime(FileNameParts(1))
Something along the lines of:
sSQL = "SELECT * FROM Table WHERE " & beginDate & " <= " & FileNameDate
I see this as preferable to adding a column to your table that contains the date substring of the FileName field, because then you constantly need to be updating that column whenever existing records are modified or new records are added. That means more clutter on the C# side, or an UPDATE query on the Access side which at least needs to get called periodically. Either way it would be more communication with the database.

How do I parse an international date string into a DateTime object? VB.NET

I have a couple DateTime inputs in a form, which display international format. For example, when a Canadian user selects a date it shows up as 17/03/2016. I'm trying to parse this string into a date (to make sure it's valid date and not something like "cat"), but the parsing function isn't recognizing the international dates as valid dates. unsubscribedFrom and unsubscribedTo are strings that are being passed in from the form, which I then pass into a SQL query
Dim unsubscribedFromDate As DateTime
Dim unsubscribedToDate As DateTime
If DateTime.TryParse(unsubscribedFrom, unsubscribedFromDate) Then
unsubscribedFrom = unsubscribedFromDate.ToEST().ToShortDateString()
PageSectionWhereClause &= "AND es.DateUnsubscribed >= CONVERT(DateTime, '" & unsubscribedFrom & "')" & Environment.NewLine
End If
If DateTime.TryParse(unsubscribedTo, unsubscribedToDate) Then
unsubscribedTo = unsubscribedToDate.ToEST().ToShortDateString()
PageSectionWhereClause &= "AND es.DateUnsubscribed >= CONVERT(DateTime, '" & unsubscribedTo & "')" & Environment.NewLine
End If
When unsubscribedFrom = "17/03/2016", DateTime.TryParse fails.
NOTE: My code needs to handle international AND non-international dates, it's possible to get both.
Generally, never use DateTime.Parse or DateTime.TryParse - because they default to using your user account's default date formatting - if you're in the US then that's MM/dd/yyyy (when pretty much the entire rest of the world uses dd/MM/yyyy).
If you know beforehand what format they're using you should use DateTime.ParseExact or DateTime.TryParseExact.
DateTime value = DateTime.ParseExact("dd/MM/yyy", input);
If you know the user is from a particular country but unsure of the format then specify an explicit CultureInfo:
DateTime value = DateTime.Parse( CultureInfo.GetCulture("en-CA"), input);

converting date format in an access table with sql update

I have a problem converting dates while updating an SQL table in VB under access: here is my code:
'Excel format date conversion
strSQL = "UPDATE tblBlotterINTLControl " & _
"SET tblBlotterINTLControl.TradeDate = CVDate(TradeDate), " & _
"tblBlotterINTLControl.SettleDate = CVDate(SettleDate);"
DoCmd.RunSQL strSQL
I obtain an error for each row: "type conversion error"
I have my tables in the right format though, please help thanks
EDIT:
I have to say that a SELECT request works but an UPDATE request doesn't! why? how?
What are the data types of the TradeDate and SettleDate fields in the Access table tblBlotterINTLControl?
SELECT TypeName(TradeDate) AS TypeOfTradeDate, TypeName(SettleDate) AS TypeOfSettleDate
FROM tblBlotterINTLControl;
Please paste that query into SQL View of a new query in Access, run it and show us what you get back.
The reason I asked is because the SET statements in your UPDATE query puzzle me.
SET tblBlotterINTLControl.TradeDate = CVDate(TradeDate)
If the TradeDate field is Date/Time datatype, using the CVDate() function on it doesn't accomplish anything.
If the TradeDate field is text datatype, CVDate() will give you a variant date, but you can't store that Date/Time value back to your text field.
Maybe you would be better off using the Format() function. Here is a sample I copied from the Immediate Window:
? Format("2011/01/01", "d mmm yyyy")
1 Jan 2011
Try CDate instead of CVDate.
CVDate actually returns a Variant of type vbDate and is only around for backwards comparability. Maybe that's what causing the problems.