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;
Related
Currently I'm getting error due to datetime format and I want in this way YYYY-M-d hh:mm:ss as a datetime format for datetime datatype but I don't know how to get that. Can You please tell me how to do that? I had a service and client developed in c#.net and both are connected with the database ms sql server and datetime is updated at runtime with current datetime.
Thanks in advance.
Use DateTime.ParseExact
var date = DateTime.ParseExact(dateTimeString,"YYYY-M-d HH:mm:ss", CultureInfo.InvariantCulture);
As you have mentioned MS Sql Server you can get current time in YYYY-MM-DD HH:MI:SS(24h) format as:
SELECT CONVERT(VARCHAR(19), GETDATE(), 120)
Here is a list of all the datetime formats in SQL Server
As for your query the below query should work
SELECT CONVERT(datetime, GETDATE(), 120)
Func<DateTime, string> GetTimeFormated = time => time.ToString("MM/dd/yyyy HH:mm").Split(' ').ToArray().LastOrDefault();
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
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.
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));
I have a column of datatype DATE in SQL Server 2008, which stores only the date in format "yyyy-MM-dd" but when I select the date from database via C# and converting into string, it shows the time part also like.
"2012-04-21 12:00:00"
what is the problem I didn't store time in database here is my query!
string sql = #"select card_no, amount, csc,expdate " +
"from user_account_card " +
"where user_id = '" + loginsession.Auser + "';";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader red = cmd.ExecuteReader();
while (red.Read())
{
loginsession.Cardno = Convert.ToString(red["card_no"]);
loginsession.Cardamount = Convert.ToString(red["amount"]);
loginsession.Csc=Convert.ToString(red["csc"]);
loginsession.Expdate = Convert.ToString(red["expdate"]);//date part
break;
}
MessageBox.Show("database value from database--" +loginsession.Expdate);
Please help me what to do
If the time is showing as midnight then for all intents and purposes it is storing it without time.
SQL has a date data type that does not include time, but you need to re-design the table. Not sure if you need/want to do that.
You could also try this:
((Date)red["expdate"]).ToString();
Since this will convert to a Date data type and not a DateTime data type you should just see the date part in the returned string.
Convert.ToString doesn't have a "date" overload, only "datetime"
SQL Server 2008 will store just date in a DATE column - you can easily verify that in SQL Server Management Studio. Also: a DATE column doesn't store a date in a particular string format - that's just how you see it. A date is a date is a date - it's stored as a date and doesn't have any "format" per se.
However, .NET doesn't have a "date-only" datatype, so reading a DATE column from SQL Server ends up in a DateTime variable in .NET which contains DATE and TIME.
So it's really not an issue of SQL Server here - but rather an issue in .NET