How to get datetime format of SQL column in C#? - c#

I want to get format of a datetime column to be able to use it in C#. I want to get it and change my variable to this format. I could not find any solution. How to get it? I just want to be able to get the format of existing column and use it as string in C#.

DateTime values in SQL Server are stored as binary values that are not human readable. They are not strings at all.
For C#, you should use the normal .Net primitive DateTime type to talk to the database; NEVER use any string formats; reserve the string for when you output to the user. The ADO.Net library (which also sits underneath other tools like Entity Framework) will efficiently and safely handle transport between your application and SQL Server.
I am building an sql query to search a string value as parameter that comes from frontend.
Great, we can do that. The way we do it to to parse the string to a C# DateTime, and then use the C# DateTime value for the query.
Let me elaborate. I'm worried you're wanting to do something like this:
string SQL = "SELECT * FROM [MyTable] WHERE [DateColumn] >= '" + TextBox1.Text "'";
var cmd = new SqlCommand(SQL, connection);
THAT IS NOT OKAY!
It is NEVER okay to use string concatenation to include user data like that. Instead, you must use parameterized queries. And when you do this, one of the things you can do is provide datetime values.
So instead, the code should look more like this:
string SQL = "SELECT * FROM [MyTable] WHERE [DateColumn] >= #MinDate";
var cmd = new SqlCommand(SQL, connection);
cmd.Parameters.Add("#MinDate", SqlDbType.DateTime).Value = DateTime.Parse(TextBox1.Text);
But even this is still a little rough, because users will do all kinds of things when entering a date into a raw textbox. You'll be much better off if you can also provide a datepicker that ensures you get a clean input from the user.
All that said, the SQL language does have specific formats for Datetime literal values. You can pick any of these formats and the database will handle it correctly:
yyyyMMdd HH:mm:ss[.fff]
yyyy-MM-ddTHH:mm:ss[.fff]
yyyyMMdd
Note the above formats are very specific and must be followed exactly, but if you do any of these can be cleanly converted to SQL Server datetime values. But again: this is not how the values are stored internally, the need for this should be relatively rare, and it's definitely NOT something you would EVER do for user input.

Related

How to insert ONLY the date (time not included) to ms access database using C#

OleDbCommand command3 = new OleDbCommand();
command3.Connection = connection;
command3.CommandText = "INSERT into AddLoad(ID_Number,Load_Added,Load_Date) values (#ID_Number, #Load_Added,#Load_Date)";
command3.Parameters.AddWithValue("#ID_Number",UserControl_AddLoadConfirmation.INumberValue);
command3.Parameters.AddWithValue("#Load_Added",addbalance);
command3.Parameters.AddWithValue("#Load_Date",DateTime.Now.ToString());
command3.ExecuteNonQuery();
I tried changing the format of my date column (Load_Date) in ms access database to "Short Date" format, when I view all datas to my Datagrid, it still comes with the hour:minute format.
im not sure with the problem maybe it's this code DateTime.Now.ToString()?
If you are going to persist a date or datetime in your database
the type in your database should be datetime (not varchar!)
You should pass DateTime types to your database directly in the command (not a string equivalent)
You should read back a datetime type when querying from the database (not a string equivalent)
So this line
command3.Parameters.AddWithValue("#Load_Date",DateTime.Now.ToString());
Becomes this
command3.Parameters.Add(New OleDbParameter("#Load_Date", OleDbType.Date) { Value = DateTime.Today });
This also ensures that you are passing the correct type to the command so it knows how it is represented in the schema. You really should not call AddWithValue as this does not pass that information in to the command.
Also keep in mind that when working with Ole (ie. access) parameters are positional and not named. That means the order they appear in in the query has to be the same order they appear in within the parameter collection.

issue with date between c# and sql converting

so i have a string "09/15/2014" and in c# it converts it to date:
DateTime from = Convert.ToDateTime(fromdate);
this outputs "9/15/2014" and when I send it over to sql I get this:
select convert(varchar, '9/1/2014 12:00:00 AM', 101)
which doesn't work for me because I need to keep any leading zero's.
help?
If you're worried about the string formats for dates with Sql Server, you're doing it wrong. As a comment to another answer indicates, SQL Server internally stores all dates in a machine-optimized numeric format that is not easily human-readable. It only converts them to a human-understandable format for output in your developer tools.
When sending dates to Sql Server, always use query parameters. In fact, when sending any data, of any type, to Sql Server in an SQL statement, always use query parameters. Anything else will not only result in formatting issues like your problem here, but will also leave you crazy-vulnerable to sql injection attacks. If you find yourself using string manipulation to include data of any type into an SQL string from client code, step away from the keyboard and go ask a real programmer how to do it right. If that sounds insulting, it's because it's so hard to understate the importance of this issue and the need to take it seriously.
When retrieving dates from Sql Server, most of the time you should just select the datetime field. Let client code worry about how to format it. Do you want leading zeros? Great! The Sql Datetime column will at some point be available in C# as a .Net DateTime value, and you can use the DateTime's .ToString() method or other formatting option to convert the value to whatever you want, at the client.
SQL queries use a date and time format which goes like this:
2014-09-15
That's year-month-day. As per the comments below, this may be different depending on the collation you have on your database (see Scott's comment for a more accurate way to describe this and get dates into this format).
DateTime's ToString method has an overload which takes a formatting string. So you can pass the format you want the string to be output to. Try it like this:
string queryDate = from.ToString("yyyy-MM-dd");
And see what you get. Use that on your query.
But if you really want this done right, use parameters. Like:
SqlCommand command = new Command(connection, "SELECT * FROM foo WHERE someDate = #date");
command.Parameters.AddWithValue("#date", from);
// where "from" is your DateTime variable from the code you've shown.
This will save you the trouble of DateTime to String conversions.

Inserting a date into a database does not work (ASPX/C#)

I have this C# code:
string RegisterDate = DateTime.Now.ToString();
RegisterDate = RegisterDate.Remove(10);
RegisterDate = RegisterDate.Replace('/', '-');
RegisterDate = String.Join("-", RegisterDate.Split('-').Reverse());
Which gives thie result: 01-06-2013
The problem is that when I try to insert it to the table I get this result: 21/06/1894
When I get the date via input it works great in the same date format, so why in this case it doesn't work?
update
If I try this:
var RegisterDate = DateTime.Today.Date;
I get Error :
Syntax error (missing operator) in query expression
Wish for help, thanks!
Don't use a string conversion at all. Assuming your data type in the database is DateTime or something similar, just use a parameter and specify its value as the DateTime in your C# code to start with. (I'm assuming you're already using parameterized SQL rather than embedding data straight in your SQL. If you're not using parameters yet, start right away!)
I'd suggest using DateTime.Today to make it clearer that you're only interested in the date part. (Note that this means that the same code running in different places could end up inserting different dates - is that okay? Normally I don't like letting the system local time zone affect things.)
You should generally avoid string conversions unless you really need a string representation of the data. At other times they just cause trouble.
EDIT: You asked for an example. It would be something like:
using (var connection = new SqlConnection(...))
{
connection.Open();
using (var command = new SqlCommand(
"INSERT INTO Foo (Name, RegisterDate) VALUES (#Name, #RegisterDate)",
connection))
{
command.Parameters.Add(new SqlParameter("#Name", SqlDbType.NVarChar))
.Value = name;
// TODO: Consider whether you really want the *local* date, or some
// fixed time zone such as UTC
command.Parameters.Add(new SqlParameter("#RegisterDate", SqlDbType.DateTime))
.Value = DateTime.Today;
command.ExecuteNonQuery();
}
}
Try
string RegisterDate = DateTime.Now.ToString("M-d-yyyy");
and then store in database.
There is no need to manually convert date to different representation. You can go through this Custom Date and Time Format Strings. But, I agree on Jon Skeet's comment below this answer:
If you want to represent a date/time type, use a date/time type. That
way you're able to take advantage of all kinds of things that the
database can do with date/time values, and you'll never get any
non-date/time values in that field.
Note:
DateTime type uses the Gregorian calendar as their default calendar. So, as pointed out by Jon Skeet, this answer won't work with other calenders(Non-Gregorian calendars).

using c# datetime in mysql update query

I'm trying to run a query from C# to MySQL (version 5.5.27) using the mysql connector for .net from the MySQL website.
The ultimate goal of the .dll I'm developing is to keep track of the rows that I've read.
The query I use to read the database is:
string strSQL = "SELECT date,ask,bid,volume FROM gbpjpy where `read` = 0";
To read in the date, I have:
DateTime dateTime = mysqlReader.GetDateTime(0);
That works fine.
The table has 5 columns, the last column is called "read". Right after the select query and parsing is done, I execute the following query:
string sqlFormattedDate = dateTime.ToString("yyyy/MM/dd HH:mm:ss");
string query = "UPDATE gbpjpy SET `read` = 1 WHERE `date` = " + sqlFormattedDate;
However, when I check my log, I have the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '01:20:08' at line 1.
The first date read in is 2012/08/30 01:20:08 (that's how it appears in the MySQL table, so that's where it gets the 01:20:08).
I've tried var sqlFormattedDate, changing the ToString overload to yyyy-MM-dd (using dashes and not forward slashes) and dateTime.ToString() all to no avail.
Why is MySQL not picking up the entire string?
Basically you should avoid including values in your query directly.
No doubt you could put quotes around the value... but you shouldn't. Instead, you should use paramterized SQL, and put the value in the parameter. That way you don't an error-prone string conversion, you avoid SQL injection attacks (for string parameters), and you separate code from data.
(As an example of how subtly-broken this can be, your current code will use the "current culture"'s date and time separators - which may not be / and :. You could fix this by specifying CultureInfo.InvariantCulture... but it's best not to do the conversion at all.)
Look for documentation of a Parameters property on whatever Command type you're using (e.g. MySqlCommand.Parameters) which will hopefully give you examples. There may even be a tutorial section in the documentation for parameterized SQL. For example, this page may be what you're after.
I suppose you have to put the whole value for the date in quotes. If you actually concatenate your query, it would look like
UPDATE gbpjpy SET `read` = 1 WHERE `date` = yyyy/MM/dd HH:mm:ss
That equal sign will only take the value until the first space.
Instead, it should look like
UPDATE gbpjpy SET `read` = 1 WHERE `date` = 'yyyy/MM/dd HH:mm:ss'
This is the particular reason in this case, however, concatenating queries like this leads to a real possibility of SQL injection. As a rule of thumb, you shouldn't do it. You can use parameterized queries and there's probably an API of the .NET connector you are using to do that.
Putting the info in a parameter allows the code to format as it needs. Likely, your original issue may have stemmed from using slashes instead of dashes in your date format. I would assume that slashes can work, but most all of the documentation I've seen has dashes separating dates with MySqlDateTimes.

executing queries with datetime in WHERE clause

I use sql server 2008 R2 as a data store.
Until now on the test machine I had the english version of the software and used to make queries formatting the datetime field as
fromDate.ToString("MM/dd/yyyy");
now I have deployed the database on another server which is in the italian language. I shall change the format in my code to
fromDate.ToString("dd/MM/yyyy");
Is there a way to make the query in a neutral format?
thanks!
EDIT:
I forgot to mention that I am using NetTiers with CodeSmith. Here's a complete sample
AppointmentQuery aq = new AppointmentQuery(true, true);
aq.AppendGreaterThan(AppointmentColumn.AppointmentDate, fromDate.ToString("MM/dd/yyyy"));
aq.AppendLessThan(AppointmentColumn.AppointmentDate, toDate.ToString("MM/dd/yyyy"));
AppointmentService aSvc = new AppointmentService();
TList<Appointment> appointmentsList = aSvc.Find(aq);
You should share the code you are using to execute the query, but I guess you are building a SQL query dynamically using string concats to build the query and the arguments. You should rather use a parameterised query then you can pass the data as a date object and no need to converto a string.
For example if your query could be something like this
DateTime fromDate = DateTime.Now;
SqlCommand cmd = new SqlCommand(
"select * from Orders where fromDT = #fromDate", con);
cmd.Parameters.AddWithValue("#fromDate", fromDate);
...
As a good side effect, this will reduce your risk of SQL injection.
Update: After your edit which does change the question context significantly, and I have to admit that I have Zero knowledge of the .netTiers project. But just out of curiosity have you tried just passing the date instances directly as in the following?
AppointmentQuery aq = new AppointmentQuery(true, true);
aq.AppendGreaterThan(AppointmentColumn.AppointmentDate, fromDate);
aq.AppendLessThan(AppointmentColumn.AppointmentDate, toDate);
AppointmentService aSvc = new AppointmentService();
TList<Appointment> appointmentsList = aSvc.Find(aq);
ISO 8601 Data elements and interchange formats — Information interchange — Representation of dates and times allows both the YYYY-MM-DD and YYYYMMDD. SQL Server recognises the ISO specifications.
Although the standard allows both the
YYYY-MM-DD and YYYYMMDD formats for
complete calendar date
representations, if the day [DD] is
omitted then only the YYYY-MM format
is allowed. By disallowing dates of
the form YYYYMM, the standard avoids
confusion with the truncated
representation YYMMDD (still often
used).
I prefer the YYYYMMDD format, but I think that's because I only knew about that to start with, and to me it seems more universal, having done away with characters that might be considered locale specific.
Personally, I always use yyyy-MM-dd. This also makes it sortable as a string.
However, a date is a date is a date. There's no need to change the date to a string. In .NET, user DateTime.

Categories