Formatting SQL friendly Date/Times in C# - c#

I am building some test scenarios for my application. In order to do this, I have some code that is generating some SQL to help me test properly. A sample of the SQL that is generated is shown here:
INSERT INTO MyTable
(
[ID],
[Name],
[CheckInDate],
[CheckOutDate]
)
VALUES
(
1,
'A title',
'Sat, 17 Dec 2011 14:33:12 GMT',
'Sat, 17 Dec 2011 15:13:12 GMT'
)
When I attempt to execute this SQL, I receive the following:
Conversion failed when converting date and/or time from character string.
How can i format the date/time strings so that SQL Server 2008 will accept them? I really need my C# code to generate the SQL (including the date/time items) to create my tests properly.
Thank you!

The way to solve this is to use the ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD for just dates (no time portion) - note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.

You can use SqlParameters.
So your command would be:
INSERT INTO MyTable
(
[ID],
[Name],
[CheckInDate],
[CheckOutDate]
)
VALUES
(
1,
'A title',
#CheckInDate,
#CheckOutDate
)
And you'd insert the dates like so:
SqlParameter checkin = new SqlParameter("#CheckInDate", SqlDbType.DateTime);
SqlParameter checkout = new SqlParameter("#CheckOutDate", SqlDbType.DateTime);
checkin.Value = DateTime.Today; // Format these to the desired dates
checkout.Value = DateTime.Today;
command.Parameters.Add(checkin);
command.Parameters.Add(checkout);

A better approach would be to not format dates at all, parameterize your insert statement, and pass dates as command parameters.

Related

SQL Server Current_Timestamp Format

I'm learning SQL Server and have an update statement where the current date and time are inserted as follows:
UPDATE data_table
SET Date_Time_Cx = CURRENT_TIMESTAMP
When it is populated in the DB, it appears "Feb 22 2018 5:07PM". How do I get to populate with the format "YYYY-MM-DD hh:mm:ss"? I looked through the SQL Server documents and lots of posts and it seems like it should be populating in the desired way. Where did I go wrong? Thanks!
Then change the type of date_time_cx:
alter table data_table alter column date_time_cx datetime2;
Then it should go into the database using the proper types. You can format the value as you wish afterwards.
I'm not sure what this has to do with C#, but here's a solution for you using base SQL.
SELECT convert(varchar, getdate(), 121)
You can find all kinds of different date and time formats from the link below.
https://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/

Convert C# Datetime to 0000-00-00 00:00:00 to MySQL

DateTime field is 'not null' in Table Structure but I want to store data (MVC C# Datetime) 0000-00-00 00:00:00 to MySQL Table without changed table structure.
I Try to do this but its but ERROR!!
Convert.ToDateTime("0000/00/00");
Please HELP , Thanks
The minimum value for .NET DateTime is January 1, 0001; the minimum for MySQL DATETIME is '1000-01-01', but in case of SQL MODE it is possible to insert '0000-00-00' as DATE, see NO_ZERO_DATE in documentation.
If you want to store '0000-00-00' in .NET DateTime structure, then use '0001-01-01', then if it is possible change this value in representation layer.
If you want to store '0000-00-00' in MySQL, then you should check SQL MODE in MySQL server -
SELECT * FROM information_schema.GLOBAL_VARIABLES
WHERE VARIABLE_NAME = 'sql_mode';
From documentation: NO_ZERO_DATE - In strict mode, do not permit '0000-00-00' as a valid date. You can still insert zero dates with the IGNORE option. When not in strict mode, the date is accepted but a warning is generated.
Server SQL Modes
You need to insert those values as string
Like this
Create table tbl(dt datetime);
Insert into tbl values('0000-00-00 00:00:00');
SELECT CAST(dt as char) FROM tbl
Fiddle
If you're asking how to create a C# DateTime object with 0000-00-00 00:00:00 - you can't, it's an invalid date. You could use DateTime.MinValue though. From memory that's 0000-01-01 00:00:00
Why not use NULL? Using magic values instead of NULL is not always a good idea.

DateTime in SQL Server CE query?

I have a date and time I'd like to insert into a SQL Server CE database, I'm trying to follow the string format yyyy-MM-dd hh:mm:ss but I get an invalid token exception when I try to insert it.
If the format is just dd-MM-yyyy everything is fine but I need to be able to add the time of day too...
It is always preferable to use Parameters:
cmd.Parameters.Add("#newTimeStamp", SqlDbType.DateTime).Value = timeStamp;

Select time value or date value from datetime with C# odbc

I have a SQL query being sent by C# system.data.odbc OdbcCommand object.
SELECT Calldate
FROM calls;
The Calldate column is a datetime type.
I want the select statement to only return the date portion of the value. The DateValue function doesn't seem to do anything. I am hoping to achieve this within the SQL provided to the OdbcCommand object.
Edit 1: The resource being queried is an access mdb file.
Given you are using sql server, you can convert the datetime
select convert(datetime, CallDate, x) from calls
x can represent different notations/numeric values for different date formatting. See this link for all the different numeric values, and the examples of their output.
http://linesofcode.net/snippets/45
EDIT (based on the fact that OP is using access, not SQL server)
You can format any string using the MS format function:
SELECT Format(CallDate,'yyyy/mm/dd') FROM calls
more formatting options here: http://www.webcheatsheet.com/SQL/access_functions/format.php
How about -
select datevalue(Calldate) from calls;
Other functions listed here

what is the correct way to format a datetime in SQL server datetime field

I have a dateTime object in C# and i want to do an insert into SQL Server datetime field. What is the correct format for this?
The correct way to do this is by using a parameterised query, not text formatting. Then you can just use a strongly-typed SqlDbType.DateTime parameter.
(If you absolutely must use text formatting to do this - and I strongly recommend against it - then something like yyyyMMdd HH:mm:ss should do the trick.)
To expand on #Luke's answer I came across this bug just the other day.
The yyyy-MM-dd HH:mm:ss format has a locale/language issue on SQL Server 2005 (an example is French), but is fixed in SQL 2008:
So, do NOT use this format: yyyy-MM-dd HH:mm:ss (space separator).
Only use: yyyy-MM-ddTHH:mm:ss ("T" separator) or yyyyMMdd HH:mm:ss (no dash delimiters)
Important if you're generating scripts that include datetime constants.
See Jamie Thomson's article on SQL Blog
use SET DATEFORMAT
a sample took from here
SET NOCOUNT ON
CREATE TABLE X(EXAMPLE INT, D SMALLDATETIME)
-- EXAMPLE 1
SET DATEFORMAT MDY
INSERT INTO X VALUES (1, '10/30/56')
-- EXAMPLE 2
SET DATEFORMAT YDM
INSERT INTO X VALUES (2, '56/31/10')
-- EXAMPLE 3
SET DATEFORMAT YMD
INSERT INTO X VALUES (3, '56/10/31')
SELECT * FROM X

Categories