Error Converting DateTime to Date - c#

I am calling a stored procedure from a WCF service using Linq-to-sql. The function signature is defined in the designer file as:
public int MS_SetTimeKeeperRecord( ... global::System.Data.Linq.Mapping.ParameterAttribute(Name="ReportDate", DbType="Date")] System.Nullable<System.DateTime> reportDate, ...)
The parameter passed to the reportDate is a C# DateTime type variable, and there is no such thing as a Date type variable. I am getting the following error from the call:
The conversion of a date data type to a datetime data type resulted in an out-of-range value
The input field is not null.
How can I make this work?

C# DateTime MinValue is 00:00:00.0000000, January 1, 0001. but if I'm not mistaken SQL min datetime value is 1753-01-01 00:00:00.000. You could get this error if you're trying to pass a value less than SQL min datetime. Also SQL max datetime is 9999-12-31 23:59:59.997 but C# max DateTime is 23:59:59.9999999, December 31, 9999.
Update:
The error is for converting from date to datetime. Date in SQL has different limits to datetime, its range is 0001-01-01 through 9999-12-31 but datetime's range is as above. So whatever the value is, it's out of range for the datetime type, although as it's mentioned in the comments you're using date.
http://msdn.microsoft.com/en-us/library/bb630352.aspx
http://msdn.microsoft.com/en-us/library/ms187819.aspx

Related

Convert Datetime string to date in SQL Server

I have a datetime data from C# like this
2019-03-20T11:25:32.0342949
I tried to convert it to datetime using cast and it triggers error
select cast('2019-03-20T11:25:32.0342949' as date)
Conversion failed when converting date and/or time from character string.
I guess its because of the T in the string.
I tried format also which of course doesn't work because its not identify it as date.
So how can I convert it properly to date. Without some substring methods to extract the date part.
You have to use DATETIME2 instead of DATETIME:
SELECT CAST('2019-03-20T11:25:32.0342949' AS DATETIME2) -- 2019-03-20 11:25:32.0342949
demo on dbfiddle.uk
The issue is the precision of the milliseconds part of your string value. You are using seven digits on the milliseconds part which is not possible on DATETIME. So you can do two things:
shorten the milliseconds part to three digits and use DATETIME
use DATETIME2 for more precision
Use the time, date, datetime2 and datetimeoffset data types for new work. These types align with the SQL Standard. They are more portable. time, datetime2 and datetimeoffset provide more seconds precision. datetimeoffset provides time zone support for globally deployed applications.
source: https://learn.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql
There is also a comparison between DATETIME and DATETIME2 on StackOverflow:
DateTime2 vs DateTime in SQL Server
If you need only date this will work
select cast('2019-03-20T11:25:32.0342949' as date) As DATE
If you need date and time this will work
select cast('2019-03-20T11:25:32.0342949' as datetime2) As DATE
Tried in Sql 15 Its working
You have to take advantage of the CONVERT() method. For example, SELECT CONVERT(date, getdate()), with date being the string you just mentioned. In your case, your datetime string takes up 10 letters of string, so you could also do SELECT CONVERT(VARCHAR(10), GETDATE(), 103). The 3rd parameter is the datetime style you want to convert to.
You should not pass datetime as string from C#, this is the correct way to pass:
string sql = "SELECT * FROM table WHERE datevalue= #date";
SqlParameter dateParam = new SqlParameter("#date", SqlDbType.DateTime);
dateParam .Value = dateValue;
SqlCommand command = new SqlCommand(sql);
command.Parameters.AddWithValue("#date", dateParam );
// then execute the command...

How to reformat Datetime when retrieving it from database using linq

I insert Datetime value into a SQL Server database with the following format: dd-MM-yy HH:mm. If I insert 01-01-18 15:30 into database and execute command
select datetimeColumn from mytable
I get back 2018-01-01 15:30:00.000. But if I retrieve all records of the table which contains the column with datetime type like
meetings = meetings.Where(m => m.meeting_name.ToLower().Contains(searchString.ToLower()));
datetime values become like 01-Jan-18 3:30:00 PM.
How can I keep datetime format the same as the format that I've inserted?
SQL Server stores data as two intergers, the first one reserved for the date and the 2nd one for the time.
meetings = meetings.Where(m => m.meeting_name.ToLower().Contains(searchString.ToLower()));
So by querying you just read date-time as is! All you need to do is to format datetime in your desired string format, for example:
var dateTime = DateTime.Now;
var dateTimeFormmated = dateTime.ToString("yyyy-MM-dd hh:mm:ss.ffff");
// 2018-01-26 05:52:54.3250
SQL Server stores the data as one or more integers, depending on the data type. Numbers are what being stored, not formatted strings. The same applies to other database providers for datetime/timestamp database types.
For instance DATETIME data type. According to SQL Server documentation, the database engine stores a DATETIME value as two integers. The first integer represents the day and the second integer represents the time. The days can range from January 1, 1753, through December 31, 9999, and the times can range from 00:00:00.000 through 23:59:59.997, with the default value being 1900-01-01 00:00:00.000.
The formatted string representation you see in say sql management studio or in any application, is done by the application showing the sql query result for you. This means that the burden of supporting different date/time formats lies with the application doing sql commands.

C# Datetime Issue to Sql

I am working on C# SQL.
I've a datetime value "1/10/2016 12:00:00 AM"
for eg
Datetime dt="1/10/2016 12:00:00 AM"
When I passed this value to SQL stored procedure as parameter, it changed to 10 Jan 2016
I need the result as 1 OCT 2016 in SQL. Sql stored procedure parameter data type is datetime.
Many Thanks
Change the datetime value and see what happened. If still coming the 10 Jan 2016, then it may be changes that stored procedure is taking the default value which is store value is 10 Jan 2016.
Use parameters to pass the values to sql query. Or use myDateTime.ToString("s"); this for datetime value
"s" - Standard datetime format
Well, are you sure that the value in c# is in fact 1 OCT 2016 and not 10 Jan 2016?
The row:
Datetime dt = "1/10/2016 12:00:00 AM";
Doesn't even compile.
Best practice for passing DateTime values between c# and Sql Server is using sql parameters of type DateTime or DateTime2 and passing an instance of the DateTime struct.
If you are doing that, then the DateTime values are guaranteed to pass correctly.

How to use DateTime with SQL queries?

How should I be using c# datetime values in my C# queries?
Up until now I've been doing the following:
Datetime my_time = new DateTime(2012, 09, 05);
cmd.Parameters.AddWithValue("#date", my_time);
cmd.CommandText = "SELECT * FROM sales WHERE date = #date";
Which has been working fine until this morning when I've been getting null errors when retrieving values from the results set.
I changed my date parameter to grab the short date string from my datetime value like this:
cmd.Parameters.AddWithValue("#date", my_time.ToShortDateString());
And it appears to be working fine again.
What is the correct way of doing this? Obviously I'm converting my datetime value to a string, only (presumably) for the database to convert it back to a datetime before evaluating my equality where clause, which seems a little pointless.
Edit:
I'm using SQL Server Compact Edition and the date field in my example has a precision setting of 8 (date, excluding time right?). Does that mean I was passing the full date with 00:00:00.000 on the end before? How might I pass a datetime value to the database without including the time, without converting to a string first?
You can just try with my_time.Date
cmd.Parameters.AddWithValue("#date", my_time.Date);
Do not pass it as a string or will run in troubles with culture formatting.
Try using SqlDateTime instead.
You're not converting the date to a string - AddWithValue knows it is a date, but it is a datetime, so it has a time component. Do your sales have a time component to them?
SELECT * FROM sales WHERE DateDiff(d, #date, date) = 0

Why can i insert MaxDate but not MinDate

when inserting into my table with a nullable datetime column, inserting DateTime.MinDate raises the error:
"The conversion of a char data type to
a datetime data type resulted in an
out-of-range datetime value."
Yet when i do MaxDate it works fine?
I actually want to insert this value as null but in PropertyInfo.SetValue() passing null value is just automatically setting as MinDate, any suggestions?
Sql Server DateTime has a range of 1753-01-01 through 9999-12-31, while .NET's DateTime from 0001-01-01 12:00:00 midnight to 9999-12-31 11:59:59 P.M.
So DateTime.MinValue is lower then the Sql Server's minimal value, while DateTime.MaxValue fits into the Sql Servers DateTime.
Use nullables: DateTime? to be able to have a null in memory.

Categories