In our app the same update is executed in a SQL Server and a SQLite database.
The issue is that SQL Server works as expected however SQLite somehow is getting always 1/1/0001.
This is the update command:
UPDATE ReviewSow
SET
SowingDate = '7/1/2016 12:00:00 AM -03:00'
WHERE
ReviewSowId = 3366;
Any idea why this could be happening?
The solution was rather odd. When converting the date to ticks and passing as a string it works perfectly! Strange but this is how SQLite works.
Example:
UPDATE ReviewSow SET SowingDate = '636263784001230000' WHERE ReviewSowId = 3366;
to convert DateTime to ticks:
((DateTimeOffset)value).Ticks.ToString()
I'm using this implementation to conduct server side searching using Entity Framework for jqGrid. The issue that I'm having is that although the search is working fine for text or numerical fields, searching using DateTime values isn't working.
The problem is that the DateTime object in my model class sends the string representation of the object (i.e. in the format 2/9/2014 12:00:00 AM) to the database but the database is formatted as 2014-09-03 00:00:00:000. As a result, the comparison always fails.
I can't change my DateTime property to a string so I'm stumped. The resultset is returned via a stored procedure (a simple SELECT * FROM [TableName]) so I tried formatting the associated Date field and returning that but it returns as an nvarchar.
Has anyone encountered this before or have any recommendations as to how to resolve this issue? I'd appreciate any help, thanks!
Just to provide an answer for anyone who comes across this. I took the following steps to resolve this issue:
1) Made the following change in the JQGrid support class:
_formatObjects.Add(parseMethod.Invoke(props[rule.field], new object[] { rule.data }));
to
_formatObjects.Add(parseMethod.Invoke(props[rule.field], new object[] { (parseMethod.ReturnType.FullName == "System.DateTime" && rule.data != "") ? Convert.ToDateTime(rule.data, CultureInfo.CreateSpecificCulture("fr-FR")).ToString() : rule.data }));
2a) In my controller, I added the following bit of code whenever I was fetching directly from the table (you have to specify the column names explicitly to truncate the time portion):
//For matching date instead of datetime values
if (wc.Clause.Contains("Date"))
{
wc.Clause = wc.Clause.Replace("DeliveryDate", "DbFunctions.TruncateTime(DeliveryDate)");
}
results = results.Where(wc.Clause, wc.FormatObjects);
2b) If the data was being returned from a stored procedure, I just returned an appropriate Date field from the SP (this approach will work for DateTime fields only if the timestamp portion is all zeros).
Hope this helps someone else.
Is there any way to see what the SQL looks like after the parameters are resolved?
For example here is a small part of my SQL:
([Event].[Start_Time] LIKE #StartTimeValue)
And my parm:
SqlDataSourceObject.SelectParameters.Add("StartTimeValue", TypeCode.DateTime, StartTimeValue)
But what does the final SQL look like when the parm #StartTimeValue is replaced with the value in StartTimeValue?
How can I see that?
Thanks for your help.
Do you have access to the database server? From there you could run a tool like SQL Profiler.
Another way is to set a break point just before the query is executed and examine the variables that went in. Usually the issue lies somewhere with the variables you're passing in (they are null, etc) and not with the resolved query itself. You could also set it up in a SQL query window like so:
-- Declare the variable to be used.
DECLARE #StartTimeValue datetime;
-- Initialize the variable.
SET #StartTimeValue = '<PASTE VARIABLE VALUE YOU GOT FROM DEBUGGING HERE>';
SELECT * FROM [Event] WHERE ([Event].[Start_Time] LIKE #StartTimeValue);
I have the following piece of inline SQL that I run from a C# windows service:
UPDATE table_name SET
status_cd = '2',
sdate = CAST('03/28/2011 18:03:40' AS DATETIME),
bat_id = '33acff9b-e2b4-410e-baaf-417656e3c255',
cnt = 1,
attempt_date = CAST('03/28/2011 18:03:40' AS DATETIME)
WHERE id = '1855'
When I run this against a SQL Server database from within the application, I get the following error:
System.Data.SqlClient.SqlException: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
But if I take the piece of SQL and run it from SQL Management Studio, it will run without issue.
Any ideas what may be causing this issue?
Ambiguous date formats are interpreted according to the language of the login. This works
set dateformat mdy
select CAST('03/28/2011 18:03:40' AS DATETIME)
This doesn't
set dateformat dmy
select CAST('03/28/2011 18:03:40' AS DATETIME)
If you use parameterised queries with the correct datatype you avoid these issues. You can also use the unambiguous "unseparated" format yyyyMMdd hh:mm:ss
But if i take the piece of sql and run it from sql management studio, it will run without issue.
If you are at liberty to, change the service account to your own login, which would inherit your language/regional perferences.
The real crux of the issue is:
I use the following to convert -> date.Value.ToString("MM/dd/yyyy HH:mm:ss")
Please start using parameterized queries so that you won't encounter these issues in the future. It is also more robust, predictable and best practice.
I think the best way to work with dates between C# and SQL is, of course, use parametrized queries, and always work with DateTime objects on C# and the ToString() formating options it provides.
You better execute set datetime <format> (here you have the set dateformat explanation on MSDN) before working with dates on SQL Server so you don't get in trouble, like for example set datetime ymd. You only need to do it once per connection because it mantains the format while open, so a good practice would be to do it just after openning the connection to the database.
Then, you can always work with 'yyyy-MM-dd HH:mm:ss:ffff' formats.
To pass the DateTime object to your parametrized query you can use DateTime.ToString('yyyy-MM-dd HH:mm:ss:ffff').
For parsing weird formatted dates on C# you can use DateTime.ParseExact() method, where you have the option to specify exactly what the input format is: DateTime.ParseExact(<some date string>, 'dd/MM-yyyy',CultureInfo.InvariantCulture). Here you have the DateTime.ParseExact() explanation on MSDN)
It's a date format issue. In Ireland the standard date format for the 28th of March would be "28-03-2011", whereas "03/28/2011" is the standard for the USA (among many others).
I know that this solution is a little different from the OP's case, but as you may have been redirected here from searching on google the title of this question, as I did, maybe you're facing the same problem I had.
Sometimes you get this error because your date time is not valid, i.e. your date (in string format) points to a day which exceeds the number of days of that month!
e.g.: CONVERT(Datetime, '2015-06-31') caused me this error, while I was converting a statement from MySql (which didn't argue! and makes the error really harder to catch) to SQL Server.
You could use next function to initialize your DateTime variable:
DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )
JAVA8: Use LocalDateTime.now().toString()
i faced this issue where i was using SQL it is different from MYSQL
the solution was puting in this format:
=date('m-d-y h:m:s');
rather than
=date('y-m-d h:m:s');
I am trying do a database update via stored procedure using ADO.NET.
Basically i setup all the parameter and command and have the one of the parameter set like the following
DbParameter nm8 = provider.CreateParameter();
nm8.ParameterName = "#EDITDATE";
nm8.DbType = System.Data.DbType.DateTime;
nm8.Value = aObject.ADateTime;
command.Parameters.Add(nm8);
In the stored procedure, the input parameter is defined as
#EDITDATE datetime = null,
and basically what the stored proc does is just get a record and update it with the EDITDATE passed in.
but i am getting this error
Error converting data type varchar to datetime.
and what i found was that the datetime value is passed in to the stored procedure as something like the following
2010-02-03 15:26:54.3100000
instead of
2010-02-03 15:26:54.310
and i think that's what is causing the casting error.
so my question is why ado.net convert the datetime in that format?
how can I resolve the issue without passing the value in as string.
thanks a lot.
Certainly this throws an error in SQL Server 2005:
print cast('2010-02-03 15:26:54.3100000' as datetime)
whereas this works fine:
print cast('2010-02-03 15:26:54.31' as datetime)
But ... is aObject.ADateTime not of type DateTime? It sounds like it's being passed to the stored procedure as a string.
If it is indeed a string, I would suggest converting it to DateTime before you pass it in:
nm8.Value = DateTime.Parse(aObject.ADateTime);
Do you have to program against the base class or can you use SqlParameter? (assuming you are using connecting to Sql Server) Maybe you can try setting the SqlDbType property
SqlParameter sqlParam = (SqlParameter)nm8; //check if it's compatible before casting.
sqlParam.SqlDbType = SqlDbType.DateTime