Conversion failed when converting date and/or time from character string - vb.net

i have been getting this error "Conversion failed when converting date and/or time from character string." on a code that previously worked untill i migrated the database to a 2008 server.
Here is the code;
query1 = "INSERT INTO RequisitionSummary (RequisitionDate, RequisitionAmount, IssuingAmount) VALUES('" & dtpRequisitionDate.value & "','" & txtRequisitionAmt.Text & "','" & txtIssuingAmount.Text & "')"
I will appreciate if the error can be spotted because i have tried different approaches including converting the value in a variable befor inserting.
Thanks
Nelson

depending on the regional setting of your server vs your computer, you will get this error if it does not match.
You might need to convert into a date and then apply a formatting to be sure it match the setting in your database.
Or you can make a SQL Convert to regional setting in the sql (look at : http://msdn.microsoft.com/en-us/library/ms187928.aspx for more details on convert)

Related

vb.net app converts dates correctly on one machine but not on another - GB/US formats

I've written an app which brings in a CSV export from our HR system, loops through all the records and applies the values from the HR system to active directory.
It works a treat, and when running on my machine i get no errors whatsoever.
When running it on one of our servers, where it is ultimately going to live and will be executed by a service account, I get date conversion errors...
System.InvalidCastException: Conversion from string "21/08/2020" to type 'Date' is not valid.
Right at the start of my code I'm defining the region...
Dim ukCulture = New Globalization.CultureInfo("en-GB")
System.Threading.Thread.CurrentThread.CurrentCulture = ukCulture
And if I query current culture at runtime, it shows 'en-GB', so that seems right.
If i write out the date strings, they all look right, and the compare operation is working fine.
The error seems to occur in this section of code...
Dim converted_hr_accountexpiry_timestamp= hr_row(0).Item("Termination Date") & ""
Dim hr_termdate_var() As String = converted_hr_accountexpiry_timestamp.split("/")
updatescript = updatescript.Replace("$x", "'" & hr_termdate_var(0) & "'") _
.Replace("$y", "'" & hr_termdate_var(1) & "'") _
.Replace("$z", "'" & hr_termdate_var(2) & "'")
So for context, this code is building up a powershell script which is executed to make the necessary changes in AD.
The section of that powershell code that we're looking at here is this...
$server = "MyPrimaryDNSServer.FQDN"
$exp = get-date -Day $x -Month $y -Year $z -Hour 00 -Minute 00 -Second 00
$expirydate = $exp.ToUniversalTime().AddDays(1)
It seems clear that its trying to use a US date format, because if the date provided would match an acceptable US date, ie 3/5/2020, then it will accept it and the wrong date will be applied. The error is only thrown when the day (dd) portion of the date would not be accepted as MM on an american format date, ie 31/07/2020.
And to re-iterate; this issue doesnt happen on my machine, only on the server that will eventually execute the application. I've been through all the region settings on that device itself and everything is set to united kingdom, with the correct dd/MM/yyyy formats for dates.
I'm at a total loss on this one and pulling out what little hair i have left.
Any suggestions/help appriciated!
EDIT 1:
This is the full exception, minus the users name obvs...
Error with account : Joe Bloggs (1010245)
System.InvalidCastException: Conversion from string "24/07/2020" to type 'Date' is not valid.
at Microsoft.VisualBasic.CompilerServices.Conversions.ToDate(String Value)
at Microsoft.VisualBasic.CompilerServices.Operators.CompareObject2(Object Left, Object Right, Boolean TextCompare)
at Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectEqual(Object Left, Object Right, Boolean TextCompare)
at Atlas.Main.GetAccountsWithUpdates()
EDIT 2:
So it looks like there are two errors occuring, which is why I couldnt find it by commenting each related line out in turn.
This is definately one of the erroring lines...
converted_ad_expiry_timestamp = converted_ad_expiry_timestamp.ToString("dd/MM/yyyy").Split(" ")(0)
The value returned is a datetime not a date, so i use tostring and split it on the space to grab just the date portion.
The second error seems to occur in here...
If Not (converted_hr_expiry_timestamp = converted_ad_expiry_timestamp) Then updateme = True : If (hr_row(0).Item("Termination Date")) = "" Then account_expiration_date = "$null" Else account_expiration_date = converted_hr_expiry_timestamp
It looks like the problem revolves around converted_ad_expiry_timestamp which seems to be a Date (the VB type is an alias for a .NET DateTime). You put it into a specific localized format via converted_ad_expiry_timestamp.ToString("dd/MM/yyyy") and then rely on automated conversion to turn it back into a Date. The way to avoid the problem you see here (where the automated conversion uses the system locale to decide the format) is to use one of the Parse or ParseExact family to control the conversion yourself. With Parse, you can specify the locale to use, or with ParseExact you can specify the format.
Similarly, when you attempt to compare them in If Not (converted_hr_expiry_timestamp = converted_ad_expiry_timestamp) Then ..., the first item in the comparison is a string; if you want to do this comparison, you need to either use ToString on the ad_expiry or parse the hr_expiry into a Date.
I would also recommend using Option Strict if you can to turn these implicit conversions into errors, or if that would introduce to many issues, at least turn on the warning for implicit conversions.
I know this is just working around the problem, and will stop it working locally for you (or rather move the problem to your machine), but if it's only ever going to be run on that server can you not just swap X and Y values?
Dim converted_hr_accountexpiry_timestamp= hr_row(0).Item("Termination Date") & ""
Dim hr_termdate_var() As String = converted_hr_accountexpiry_timestamp.split("/")
updatescript = updatescript.Replace("$x", "'" & hr_termdate_var(1) & "'") _
.Replace("$y", "'" & hr_termdate_var(0) & "'") _
.Replace("$z", "'" & hr_termdate_var(2) & "'")
Alternatively, if you want it to work on both systems then maybe a check before running the offending code is in order, something like this has worked for me in the past:
Try
Dim TempTimeString As String = "31/01/2020 01:00 AM"
Dim ConvertedTime As Date
ConvertedTime = DateTime.Parse(TempTimeString)
'''Don't swap X and Y as it was able to convert
Catch ex As Exception
'''swap X and Y as it was unable to convert
End Try

Error converting Nvarchar data type to datetime from VB.NET

I have a problem regarding dates from my program to a stored procedure in SQL.
My program takes a date from the excel spreadsheet and parses it as such:
tempDate = Date.FromOADate(exWS.Cells(exRow, myMatchedColumns(2)).value)
Dim format() = {"dd/MM/yyyy", "dd-MM-yyyy", "yyyy-MM-dd"}
dueDate = Date.ParseExact(tempDate, format,
System.Globalization.DateTimeFormatInfo.InvariantInfo,
Globalization.DateTimeStyles.None)
dueDate is 'DATE' variable so I'm assuming at this point the 'dueDate' is a universal Date object. I think this was the best way to parse BOTH English regional date and Polish dates, since this will be used on a Polish machine.
However, when sending values to my stored procedure:
mySQLString = "EXEC bsp.PartPrice_sp " & _
"'" & dueDate & "', " & _
"'" & myPartID & "', " & _
"'" & currency & "'"
English sends EXEC bsp.PartPrice_sp '01/09/2015', 'L555', 'USD' which returns the price.
Polish sends EXEC bsp.PartPrice_sp '2015-09-01', 'L555', 'USD' which incurs the error:
The conversion of a nvarchar data type to a datetime data type
resulted in an out-of-range value.
I understand the error, but the next execution of the stored procedure, the Polish machine sent 2015-09-10 which returned a price fine. I'm guessing since 2015-10-09 is still within range but interestingly it returned the correct price for 10th September 2015.
Nevertheless I'm struggling to find a universal way of executing the stored procedure in both English and Polish. Any help you can give to parse the dates correctly which also makes SQL happy would be awesome.
Thanks.
Program written in VB .NET.
P.S If I change the #duedate in the stored procedure from nvarchar to datetime, I get an:
Error converting data type varchar to datetime.
Error, which I'm guessing is from the English format. Many thanks.
Date formats in inline non-parameterised queries are one of those things that can drive you spare in my experience.
So -
If at all possible issue a SqlCommand with a collection of SqlParameters, into which you add the actual Date-typed .Net variables. Much safer.
If you really have to keep the inline SQL for some reason, never pass in regionalised date formats. They reliably break for odd reasons. Ideally send the server YYYY-MM-DD hh:mm:ss.ms, but to be safe run that through a centralised function - partly it's easier than making sure you're calling the right .ToString() format in all places correctly, partly I've in the past had occasional servers complain even at that format.

From Access 2002 to Access 2010 Conversion failed when converting date and/or time from character string

I am working on this Access 2002 database. It uses linked servers to SQL Server 2008. I am having a problem where in load of the main form it does a DLookup and looks at a date.
EndDate = Nz(DLookup("End_Date", "Employee", "EmpID= " & EmpID & " AND End_Date IS NOT NULL AND End_Date < #" & Now & "#"), "")
Now this works fine in Access 2002, but in Access 2010 I get the:
Conversion failed when converting date and/or time from character string
Here's the kicker though, it works in Access 2010 for one user: myself. No other users does it work for and also other installations with Windows 7 and the Access 2010 Runtime work fine. On the same machine the MDB works correctly also. If I replace the Pound signs with single quotes like in SQL Server it runs fine on the 2010 machine but no longer works on 2002 (duh).
It's just been wracking my brain and normally I have been able to get it to work by uninstalling all of Office and then reinstalling and making sure the SP1 for the Access Runtime was installed last.
Instead of transforming the value of Now() to a string in your DLookup, just let the db engine determine Now() for itself.
EndDate = Nz(DLookup("End_Date", "Employee", _
"EmpID= " & EmpID & " AND End_Date IS NOT NULL AND End_Date < Now()"), "")
That approach does not depend on a conversion between Date/Time and string and back again, so will avoid the problem you reported.
If you want to examine how the original DLookup gave different results, try something like this on the different machines:
Dim strCriteria As String
strCriteria = "EmpID= " & EmpID & " AND End_Date IS NOT NULL" & _
" AND End_Date < #" & Now & "#"
Debug.Print "strCriteria: " & strCriteria
EndDate = Nz(DLookup("End_Date", "Employee", strCriteria), "")
After running that code, go to the Immediate window (Crtl+g) and inspect the value of strCriteria.
Note that the type of date / time field that you are using in SQL Server may cause problems, which could explain the difference between versions.
Access 2010 provides limited support for four new date/time data types
that were added in SQL Server 2008:
TIME
DATE
DATETIME2
DATETIMEOFFSET
-- http://office.microsoft.com/en-us/access-help/create-an-access-project-HA010341589.aspx#_Toc257281378
If you are storing the dates in SQL server as the data type “Date” or
“Date2” try changing them to “DateTime” I had this problem linking
data from SQL server 2008R2 to access 97, access did not see it as a
date and treated it like text
-- MS-Access front-end does not recognise dates from SQL Server
As an aside, there is no need for End_Date IS NOT NULL, once you add another criterion, null values will be excluded unless you specifically include them.

Access/VBA and SQL WHERE clause format issue

I have read a huge pile of problems and solutions, and I just can't figure out what I'm doing wrong.
BounceDate = DateValue(txtBounceDate.Value)
bncSql = "DELETE _BounceMaster.* FROM _BounceMaster" & _
" WHERE _BounceMaster.DateCheck >= #" & BounceDate & "#;"
DoCmd.RunSQL bncSql
_BounceMaster.DateCheck is in Date/Time format, which I think may be the issue, but I can't figure out what different format it should be in, or how to get there. As best as I can tell, BounceDate is correct - even using CDate didn't make a idfference. I have gotten both data mismatch errors, and currently, with code as above, I am getting syntax errors. What am I doing wrong?
I suppose the problem comes from date formatting. The BounceDate variable is DateTime type, so when you concatenate with string type variable, VBA automatically casts DateTime variable into String type using date format from your regional settings.
As I correctly remember, SQL interpreter from MS Access feels comfortable only with mm/dd/yyyy date format, so please try this:
BounceDate = DateValue(txtBounceDate.Value)
bncSql = "DELETE _BounceMaster.* FROM _BounceMaster" & _
" WHERE _BounceMaster.DateCheck >= #" & Format(BounceDate, "mm/dd/yyyy") & "#;"
DoCmd.RunSQL bncSql
It should be
DELETE FROM _BounceMaster
not
DELETE _BounceMaster.* FROM _BounceMaster
You should be using parameterized queries, as your code is subject to SQL injection attack.

dd/mm automatically got changed to mm/dd

I coded something using Date statement in Access VBA. It was working fine until the start of this month, but now I am seeing that the Date has automatically changed the format from dd/mm/yyyy to mm/dd/yyyy. Has anyone else encountered the same problem?
The default Access SQL date format, regardless of locale, is mm/dd/yyyy. If you use an invalid date format, it will 'helpfully' try to convert that to a valid date for you.
So, if you use '30/09/2008', it will recognize you're using dd/mm/yyyy, and convert it appropriately. However, a value like '10/01/2008' is a valid mm/dd/yyyy value to begin with, so it will not be converted, and stored incorrectly in case you actually meant dd/mm/yyyy....
The solution is to always convert your date values to a mm/dd/yyyy string prior to using them in Access SQL statements. You have to be a bit careful here, as using VBA date format masks may not work entirely as you'd expect on non-US locales (e.g. 'helpfully' interpreting "mm/dd/yyyy" as "the localized short date format"), so please test carefully using your particular Access/VBA version.
Access requires a date to be unambiguous. It is generally recommended that you use yyyy/mm/dd, regardless of locale. For example:
strSQL="SELECT SomeDate FROM tblT WHERE SomeDate=#" & Format(DateVar, "yyyy/mm/dd") & "#"
Try this code:
stLinkCriteria = "[ProjectDate] Between #" & Format(CDate(Me![txtDateFrom]), "mm/dd/yyyy") & "# And #" & Format(CDate(Me![txtDateTo]), "mm/dd/yyyy") & "#"
It works for me.
This works:
sentenciaSQL = "UPDATE Numeraciones " & _
"SET Valor = " & Valor & ", " & _
"Fecha = #" & **Format(fecha,"mm/dd/yyyy HH:nn:ss") & "#, " &** _
"Id_Usuario = " & Id_Usuario & _
" WHERE Nombre = '" & Nombre & "'"
I have been very successful using the datevalue() function. When getting dates from unbound controls it seems to be clever enough to interpret the format "dd/mm/yyyy" correctly. Thus, a Jet SQL query like
"Select * from DateTable where StartDate = datevalue(" & me!TxtStartDate & ");"
seems to work every time.
I was experiencing same issue while trying to build a SQL string through VBA.
My locale settings use dd/mm/yyyy and I was trying to put into SQL statement data taken from an unbound textbox in a form.
The issue was due to the fact I was declaring, let's say, varMyDate as "date" type, so the engine reverted the format back even after the format.
Since you are really building a string the logical and proper data type is "string", and that solved the problem.