Convert Datetime string to date in SQL Server - c#

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...

Related

C# SQL Server compare date with string

I have to compare a table field that is a date stored as varchar in the format 'dd/MM/yyyy' with a date value, but the comparison fails. I have exception
Conversion failed when converting date and/or time from character string.
I tried converting the date to compare i nstring, like this
string dateFormat = date.ToString("dd/MM/yyyy");
and then write the query like this:
string sql = "select * from TB_RICHIESTE where CONVERT(DATE, Date) <= CONVERT(DATE, '" + dateFormat + "')";
But I have this excpetion. Someone can help me? Thanks
First, you should not store dates as strings.
As Panagiotis Kanavos wrote in his comment - this is a serious bug. You can't sort by such a column, you can't search for date ranges, and most important - you can't control if someone enters an invalid value - nothing is stopping someone from entering "Alfredo" to that column.
For more information, read Aaron Bertrand's Bad habits to kick : choosing the wrong data type.
Second, you should not pass dates from .Net to Sql server as strings. you should pass instances of DateTime as parameters.
The .Net DateTime maps directly to SQL Server's Date.
If you can't change the data type of the column, you can at least convert it to date using the proper convert style (103 in your case).
Here is a better way to do it:
var sql = "select * from TB_RICHIESTE where CONVERT(DATE, [Date], 103) <= #Date";
Then you add the #Date parameter to the SqlCommand:
com.Parameters.Add("#Date", SqlDbType.Date).Value = date.Date;
Use Parameter to pass date values refer #Zohar Peled post. This is the proper method handling date values.
OR
You can pass the date value in ISO format, refer the below code.
string dateFormat = date.ToString("yyyy/MM/dd");
string sql = "select * from TB_RICHIESTE where CONVERT(DATE, Date) <= CONVERT(DATE, '" + dateFormat + "')";

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

Insert into database date with another format

I have a gridview and sqldatasource.
I'm trying to insert new records in database and the Date column type is Date and default format is US , mm/dd/yyyy and I'm trying to insert a date with another format.
SqlDataSource2.InsertCommand = "Insert into test (Name,Date) VALUES (#Name,#CONVERT(Date,'#Date',104))";
SqlDataSource2.InsertParameters.Add("Name", nameText);
SqlDataSource2.InsertParameters.Add("Date", DbType.DateTime, date.Text);
I get: String was not recognized as a valid DateTime.
Thanks
The Date type in format agnostic in the database (unless you store it as a string).
You may first try to get a valid System.DateTime object using DateTime.ParseExact or DateTime.Parse.
Then, set the SqlParameter with this value.
DateTime dateValue = DateTime.Parse(date.Text); // try to make this working first.
SqlDataSource2.InsertCommand= "Insert into test (Name,Date) VALUES (#Name,#Date)";
SqlDataSource2.InsertParameters.Add("Name", nameText);
SqlDataSource2.InsertParameters.Add("Date", DbType.DateTime, dateValue);
First you should use DateTime object instead of Date.Text, First convert your text into DateTime
Second you don't need to format date time while inserting if the data type is datatime at SQLServer table just use.
"Insert into test (Name,Date) VALUES (#Name, #Date)";
You should format date time while retrieving data in select

Parse DateTime Parameter

I have a variable which is datetime type. How can i get the shortdatetostring() as datetime variable type ? I have a column in databae as datetime type. I would like to get the records which are added at a certain day.
Example:
SELECT id FROM database WHERE added like #p1
The parameter of the query is a datetime variable.
Match based on day, month, and year of the date variables. Do not use strings, since matching is slow.
SELECT id
FROM database
WHERE Datepart(yy, added) = Datepart(yy, #p1)
AND Datepart(mm, added) = Datepart(mm, #p1)
AND Datepart(dd, added) = Datepart(dd, #p1)
You could do something like this in order to get all the ids on the 26th of January.
SELECT id FROM database WHERE added >= '2012-01-26' and added < '2012-01-27'
In C# you do like below.
DateTime dt;
string Temp1 = "Your Date";
if (DateTime.TryParse(Temp1, out dt))
{
// If it is a valid date
string date = dt.ToShortDateString();
string time = dt.ToShortTimeString();
}
In SQL Server
SELECT id FROM database WHERE Datepart(dd, added) = Datepart(dd, #p1)
Please see below the sample
create table #temp
(
dat datetime,
)
insert into #temp(dat)values(GETDATE())
insert into #temp(dat)values(GETDATE()+1)
insert into #temp(dat)values(GETDATE()+2)
select * from #temp where DATEPART(dd, dat) > 27
drop table #temp
If you are using parameterised queries the format of the datetime type doesn't matter.
Got to remember that "2012-01-26" is a string not a date....
If you need a Date formatted a particular way, then myDateTime.ToString(....), there are several overloads, one of which is simply a format String e.g. "yyyy-MM-dd"
If you want to parse a string into a datetime then DateTime.Parse(...), again there are several overloads.
More on dates after comment
DateTime.Parse("12/31/2012") gives you a datetime type in c#.
It parses the string into a DateTime
MyDateTime.ToString("MM/dd/yyyy") gives you a string of date in the specified format.
"31/12/2012" is not a date, if you want it as a date, then you Parse it into one.
Now which way do you want to go DateTime to a string, or string to a DateTime, or are you asking something completely different?
If you want to only Parse DateTimes trhat are in the format mm/dd/yyyy, you can't because when it's string there's absolutely no way to tell the 6th of August from the 8th of June, unless you assume the format is always mm/dd/yyyy which is pretty much guaranteed to go badly wrong at somepoint, which is why when going from Date to String YYYYMMDD or YYYY-MM-DD are the way to go.
If it's what you want / have to do then
DateTime MyDateTime = DateTime.Parse("12/31/2012",CultureInfo.CurrentCulture);
Pass a string in a format that doesn't fit the pattern and it will throw an exception, NB that would include "31/12/2012".
CultureInfo is in the System.Globalisation namespace.
There area number of options. Current, CurrentUI, Invariant etc. Which one you use depends on how you are setup and globalisation / internationalisation requirements (even if they are none). So using Current Culture, would assume US default regional settings. But if I was to run your code, then "31/12/2012" would work and "12/31/2012" would blow chunks.
If you want to fix the formats no matter what system they are run on then InvariantCulture is the way to go. Don't forget to set the neutral language as well. Hit the assembly button on the Applications tab of the project's property pages. Neutral language is a drop down near the bottom. Presumably you want en-us.
If you don't want the excpetion then it's
DateTime myDateTime;
if (DateTime.TryParse("12/31/2012",CultureInfo.CurrentCulture, out myDateTime)
{
// do something with myDateTime...
}
else
{
// do something about the value not being in the correct format
}
You might be able to simplify this by editing the query, actually. Try
select id from database where cast(added as date) = cast(#p1 as date)
This (effectively) strips the time from added as well as the time from #p1 and compares the dates only.

Oracle date formatting

in my c# programme i am requesting data from an oracle database and one field is the date abd time in this format - 12/09/2008 15:11:17 , is there anyway i can just return the date?
Is there also a way of ensuring its in british format, by modifying the sql to be dd/mm/yyyy
thanks
You could get the date part of the DateTime using C#, You could do
string date = MyDateTime.ToString("dd/MM/yyyy");///let MyDateTime be your DateTime variable
If you want to do in Oracle, you can use to_char for example,
select to_char(sysdate, 'dd/MM/yyyy') From dual;
The Oracle trunc() function removes the time part:
select trunc(datecol) from mytable;
In your sql query to oracle you can
to_date('12/09/2008 15:11:17', 'dd/MM/yyyy')
where you replace the date with your field in the oracle db.
Alternatively, you can handle it on the C# side with formatting
CultureInfo ukCulture = new CultureInfo("en-GB");
//this assuming you do not have a datetime type
DateTime myDateTime = DateTime.Parse("12/09/2008 15:11:17", ukCulture.DateTimeFormat);
string result = myDateTime.ToString(ukCulture.DateTimeFormat.ShortDatePattern));

Categories