Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL server DateTime and C# DateTime

Tags:

c#

sql

On my SQL server I have a very simple table for testing, which only contains three rows: ID, Date and Hours.(varchar, DateTime, varchar).

The DateTime format in SQL is like: yyyy-MM-dd HH:mm:ss.fff.

The DateTime format in C# is like: yyyy-dd-MM HH:mm:ss.fff.

I use the following code to get C# DateTime format:

 string ddd = "2012-10-10 00:00:00.000";
 dt1 = DateTime.ParseExact(ddd, "yyyy-MM-dd HH:mm:ss.fff", null);

If I try to make it into yyyy-dd-MM I get an error:

The DateTime, which is represented by the string, isn't supported by the calender.

In my C# application is am trying to find total amount of hours between sunder dates. I sort of got it to working, but it only works for dates between 01 and 12.

So like from 2012-01-10 to 2012-10-10 (ten days) will give me the correct amount of total hours from the database.

But when I write 2012-01-10 to 2012-14-10 (fourteen days) I get an error:

The conversion of a char data type to a datetime data type resulted in an out-of-range"

Thank you in advance.

PS. Can you suggest a easier way to get dates?

mySQL query

string CommandText = "SELECT * FROM date_test WHERE id = '4' AND date BETWEEN '" + dt1 + "' AND '" + dt2 + "'";

I have figured out the problem but not the solution.

The problem is that SQL database looks at the format, and wants yyyy-MM-dd, but C# can only send yyyy-dd-MM.

Why cannot ParseExact() do yyyy-MM-dd?

like image 333
Pavenhimself Avatar asked Sep 24 '12 11:09

Pavenhimself


People also ask

How does SQL Server store datetime?

SQL Server comes with the following data types for storing a date or a date/time value in the database: DATE - format YYYY-MM-DD. DATETIME - format: YYYY-MM-DD HH:MI:SS. SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS.

What is difference between datetime and datetime2 in SQL Server?

Microsoft recommends using DateTime2 instead of DateTime as it is more portable and provides more seconds precision. Also, DateTime2 has a larger date range and optional user-defined seconds precision with higher accuracy. Datetime2 aligns with SQL standards.

What is SQL datetime?

The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts.


1 Answers

You're preparing a perfect ground for SQL injections.
Also look here. There's an example of parametrized query.

like image 77
Dennis Avatar answered Oct 15 '22 11:10

Dennis