Datetime conversion giving error - c#

consider me a beginner in c#
I am doing some changes in a pre developed software (C#.Net) , we are saving data by datewise , Currently in insert query (build in c#) we are passing GETDATE() to save today date , but now we have to save data on the basis of a different date.
When I am building query in c# , I m passing that a datetime variable into query
after conversion , conversion as follow
Date_Stamp = DateTime.ParseExact(dt.Rows[0][0].ToString(), "MM/dd/yyyy HH:mm:ss tt", new CultureInfo("en-IN"));
but it is showing error "String was not recognized as a valid DateTime.".
The reason to convert is coz these date field are getting displayed in format ToString("yyyy-MM-dd"));
Which will give 2017-07-13 14:56:30.233 as 13-jul-2017 on front end (as per requirement). We cant change this part of code as it is being used in lot of places , hard to change .
Problem is
variable storing value as
2017-12-07 00:00:00.000
which give after conversion 07-Dec-2017 [wrong - it is needed as 12-jul-2017]
GETDATE storing value as
2017-07-12 14:56:30.233
which is after conversion coming right as 12-jul-2017
I know there is no datetime format in sql server when it come to storing data
But can we store value from variable [2017-12-07 ] as [2017-07-12 ] ?
How GETDATE() give us date in year-month-date format
?

Neither .NET's nor SQL Server's date related type have any format. All of them are binary values, just like integers and decimals. Formats apply only when they are explicitly or implicitly converted to strings, or parsed from strings.
Assuming your query looked something like SELECT GETDATE(), ... and you loaded the results to an DataTable, the values will be returned as DateTime values. If you used a strongly-typed DataTable you could just use the value. With a generic DataTable the value will be boxed and return as an object.
All you have to do is just cast the field value to DateTime :
Date_Stamp = (DateTime)dt.Rows[0][0];
This will also work for date and datetime2 types. datetimeoffset is returned as DateTimeOffset. time is returned as TimeSpan.
The problem in the original is caused because the field value is formatted into a string using the current culture dt.Rows[0][0].ToString() first. Then ParseExact is called trying to parse it using a different format. A simple DateTime.Parse(dt.Rows[0][0].ToString()) would have worked (even though it would be wasteful), since both DateTime.Parse and DateTime.ToString() use the same culture.
UPDATE
Reading date fields from a table has no issues - the values are returned using the appropriate date type. For example, running SELECT StartDate from ThatTable will return DateTime if the table's schema is :
CREATE TABLE ThatTable
(
ID int,
StartDate datetime
)
Problems are caused if, instead of using the correct type, dates are stored as strings in VARCHAR columns. That's a serious bug that needs to be fixed. There is NO assurance that the strings can be parsed to dates at all, or that they follow the same format. It's all too easy for some faulty application code to use eg DateTime.Now.ToString() and store a localized string in there.
Even if the format is the same, it's just wasteful and unreliable. The string takes more storage than the equivalent type, introduces conversion issues, prevents the use of date functions, and the server can't apply date optimizations to queries and indexing.

Related

What does casting a string to DateTime in an Entity Framework Core LINQ query return?

My application uses Entity Framework Core to load data from an SQL database. To avoid loading all data entries of my table Schedule and filter them afterwards, I would like to filter them in the database query by comparing the Schedule.Date entry, which is a string, to a previously created DateTime object named targetDate. Since it is not possible to directly use DateTime.Parse to convert Schedule.Date to a DateTime in this query, I instead cast it to an object and then DateTime explicitly. The following line represents what I'm doing:
Schedule schedule = _context.Schedule.Where(s => (DateTime)(object)s.Date >= targetDate).First();
This works fine for now. However, I don't want to run into problems later, so I need to understand which format the cast to DateTime uses in this case. Though the dates in the database are strings, they are all provided in the format en-US and casting them appears to use just this format, which would be great. How can I be sure that it always uses this format and how is the format to be used determined when using a cast like this?
Assuming you are using SQL Server
Though the dates in the database are strings,
Which is bad for a number of reasons. Here you'll require a table scan to convert all the strings to dates to perform the comparison.
they are all provided in the format en-US and casting them appears to use just this format, which would be great. How can I be sure that it always uses this format and how is the format to be used determined when using a cast like this?
The conversion is done in SQL Server which will convert strings to dates based on the current language of the connection.

Need C# to save date into sql server as sql server datetime e.g. 2016-05-19 12:46:08.610

I need to have C# via Entity Framework save current datetime to sql server into table column of datatype datetime
Was reading that DateTime.Now in C# is not going to be correct ...
so I stumbled across where a guy posted that he was doing this as it saves down to the proper millisecond
System.Data.SqlTypes.SqlDateTime entry2
= new System.Data.SqlTypes.SqlDateTime(new DateTime(dto.LookUpDateTime));
DateTime entry = entry2.Value;
Now I assumed with the Overloads that I should be able to just do this:
System.Data.SqlTypes.SqlDateTime dt
= new System.Data.SqlTypes.SqlDateTime(new DateTime());
However, I get an error in catch block saying 'sqldatatime overflow...`
DateTime dateTime = dt.Value;
rpmuser.lst_pwd_chg_dtm = dateTime;
rpmuser.cre_dtm = dateTime;
Can I use DateTime.Now or what do I need to do to get this SqlDateTime to work?
This is almost certainly because you are trying to store a date that is outside the supported range. On MS SQL Server the datetime field type can hold datetime values in the range 1-Jan-1753 00:00:00 to 31-Dec-9999 23:59:59.997 inclusive. This is narrower than the range explicitly supported by the .NET DateTime type (1-Jan-0001 00:00:00 to 31-Dec-9999 23:59:59 plus a fraction). So any date prior to 1-Jan-1753 will cause that error.
A common problem is when you use either DateTime.MinValue to indicate a specific state of your data but don't filter that to something the SQL field can contain before sending the data to the database. The solution in this case would be to define a suitable lower boundary of the data and define a static value that is lower but still within the SQL range.
If your data needs to include dates and times outside of the valid range for the SQL datetime field type then you might want to use the datetime2 field type which has the same effective range as the .NET DateTime type. Which is unsurprising since it appears to be the same data structure - count of 100ns ticks since 1-1-1.

Cannot pass date into stored procedure

Trying to pass date into a stored procedure as follows:
#dateRegistered = '28/04/2012'
But it keeps telling me:
Error converting data type varchar to date.
It works if I do it as:
#dateRegistered = '04/28/2012'
But this is not the format I want to use.
I have run the following query to set the format:
SET DATEFORMAT dmy
Why isn't it working?
Edit: Here is how I did it:
In my stored procedure, I put:
SET DATEFORMAT dmy
Then from code, I pass it as:
myCommand.Parameters.Add("#dateRegistered", SqlDbType.Date);
myCommand.Parameters["#dateRegistered"].Value = DateTime.Now.ToString("dd/mm/yyyy");
I passed it as string to ensure that even if my computer (or the server) has a different date format, it will always use dmy.
Edit Edit:
I passed it as datetime.now. It seems to transform it to the default format when I send it, and then transform it back to my computer format when I read it. Unsure how exactly this happens, but it seems to be working fine.
It looks like the parameter is a date (in the database), while you try to pass a string (which corresponds to varchar in the database). If you instead pass a .NET DateTime object it should work as expected.
Save yourself the headache and use an unambiguous date format - 20120428 (YYYYMMDD) or 2012-04-28.
As an aside: you mention you're using C# (based on the tags) - how are you using ADO.NET? Or is it Linq to SQL / EF / some other ORM?
Edit:
Ok, use the CONVERT function with an appropriate parameter indicating the format of your date string
EG:
declare #D datetime
set #D = CONVERT(datetime, '04/28/2012', 101)
print #D
101 is US standard format mm/dd/yyyy.
Using convert will ensure it ALWAYS works regardless of any environment settings such as the date order.
If you call set dateformat dmy, that only affects the current connection. You'd have to set it every time right before you convert the string to a date.
The best solution is probably the ISO format, like #IanYates suggests.
dear your code is working after using
* SET DATEFORMAT dmy
because you are passing date as "dd/MM/yyyy"
like "DateTime.Now.ToString("dd/mm/yyyy")"
check the date format in your database by following command :-
dbcc useroptions
and check "dateformat : mdy" by default. So passing your date in "MM/dd/yyyy" format will also work fine.
Happy Coding :)

How to get datetime records in "dd/mm/yyyy h:m:s" format FROM SQL server 2005?

I want to get records from sql server 2005 in datetime format like this "dd/mm/yyyy h:m:s"
My database date is default datetime format
AttLogId int
...
DownloadLog datetime
I am trying to retrieve the datetime like this:
SELECT AttLogId ,convert(varchar,DownloadLogDate,103) FROM AttLog
ORDER BY DownloadLogDate
but I only get the date and not the time.
I suggest you don't try to get the values in a particular string format. Fetch them as DateTime values and then format them in the .NET code using DateTime.ToString("dd/MM/yyyy H:m:s").
It's almost always worth keeping data in its "natural" data type (date/time here) for as long as possible, only converting to text when you really need to. So your SQL should just be:
SELECT AttLogId, DownloadLogDate FROM AttLog
ORDER BY DownloadLogDate
How you then retrieve the data will depend on how you're talking to SQL (e.g. LINQ to SQL, using SqlDbReader etc). But you should be able to get it as a DateTime and then format it locally. This will make it easier to test, easier to debug, give you more control over cultural aspects (date separators, possibly specifying a standard specifier instead of a custom one, etc).
it is because you are using 103 , so it will give only date .
if you want more format check this :
http://msdn.microsoft.com/en-us/library/ms187928.aspx
According to need, u can try this
SELECT AttLogId , convert(varchar(10),DownloadLogDate,103) +' '+ convert(varchar(8),DownloadLogDate,108) FROM AttLog ORDER BY DownloadLogDate
Note : firstone is for date and second one is for time in H:M:S
hope this help u..

How to apply Datetime comparison on varchar Datatype in C#

I want to apply datetime comparison on a field which is of type varchar in SQL Server database. I want to know how can i apply this, for example my query is something like this
from Pos in TableName
where Pos.vcr_Value >= Convert.ToDateTime("UserInputDate") //UserInputDate = 02/02/2011
select Pos;
If i try this it works
from Pos in TableName
where Pos.vcr_Value == "UserInputDate" //UserInputDate = 02/02/2011
select Pos;
But this just matches the date i want to get all the records after UserInputDate variable
Note:
This field store variable type of data sometime it save string sometime datetime
As others have said, your database design is fundamentally poor. Given that the column may not even be a date at all, you'd need to use DateTime.TryParse or DateTime.TryParseExact to write something which would work in LINQ to Objects. In LINQ to SQL that won't work as you'd need to use a lambda expression with a block as the body, and that can't be converted into an expression tree.
Furthermore, you've also got the problem of knowing what date format to expect - which is a natural corollary of storing dates in a text-based field instead of as a native date-based field.
If your date format were yyyy-MM-dd (or yyyy/MM/dd) it would be possible to do something which at least approximated the right query, by doing a string comparison, e.g. saying the value had to be between "2011-02-02" and "2099-12-31" for example. Even then it would match values such as "201 this isn't really a date".
If you don't have too many records, you could always do the filtering at the .NET side instead of in SQL - it's not ideal, but if you have to work with a broken schema, it's probably the most reliable option. If at all possible, however, you should change how you store the data.
Fix you database. Convert the varchar field to DateTime
check here There are answers how to convert and compare dates
HTH
Ivo Stoykov
PS: Steve is right. date format kept in DB as varchar is very bad practice!

Categories