I have a problem with inserting a date time from my web app, using C# to my database with SQL Server 2008.
My machine is set to Hebrew but I also tried to change to en-us culture. It's a conversion thing I know, but can't figure out how to pass it correctly.
In the database, the column is declared as DATE NOT NULL,
This is how I try to pass a date from C# by using a dataset:
newDR["Close_Date"] = Convert.ToString(this.closeDate.Date.ToString("YYYYMMDD"));
Any ideas?
Don't convert it to a string at all. Keep it as a DateTime. Try to avoid using string conversions as far as you can - every string conversion is a potential source of problems.
So:
newDR["Close_Date"] = closeDate.Date;
Related
My application uses Entity Framework Core to load data from an SQL database. To avoid loading all data entries of my table Schedule and filter them afterwards, I would like to filter them in the database query by comparing the Schedule.Date entry, which is a string, to a previously created DateTime object named targetDate. Since it is not possible to directly use DateTime.Parse to convert Schedule.Date to a DateTime in this query, I instead cast it to an object and then DateTime explicitly. The following line represents what I'm doing:
Schedule schedule = _context.Schedule.Where(s => (DateTime)(object)s.Date >= targetDate).First();
This works fine for now. However, I don't want to run into problems later, so I need to understand which format the cast to DateTime uses in this case. Though the dates in the database are strings, they are all provided in the format en-US and casting them appears to use just this format, which would be great. How can I be sure that it always uses this format and how is the format to be used determined when using a cast like this?
Assuming you are using SQL Server
Though the dates in the database are strings,
Which is bad for a number of reasons. Here you'll require a table scan to convert all the strings to dates to perform the comparison.
they are all provided in the format en-US and casting them appears to use just this format, which would be great. How can I be sure that it always uses this format and how is the format to be used determined when using a cast like this?
The conversion is done in SQL Server which will convert strings to dates based on the current language of the connection.
I'm trying to find a way to correctly format a Date in a SELECT statement that loads data from an old Visual Fox Pro Database. I need to do this so that I can load it into a CSV, then load it into MySQL, which takes the date format 'yyyy-MM-dd'.
This is my query at the moment;
var dbfCmd = new OleDbCommand(#"SELECT ct_id, ct_cmpid, ct_empid, ct_pplid, ct_cntid, ct_pplnm, ct_date, ct_time, ct_type, ct_doneby, ct_desc FROM contacts", dbfCon);
I need to find a way to format the ct_date column. I've tried a number of ways so far, including using FDATE and FORMAT, but nothing has worked so far. I've looked through the supported commands for OleDB but still haven't come across anything.
Can anyone inform me of the correct way to format the Date query so that I can import to MySQL?
Do not format the date on the server.
Receive as a date column, then read as a DateTime value when enumerating the query. Finally format it on your client in the specify way when writing the file.
Although it has been suggested to convert the data in C# to date format, if you REALLY want to pull the date formatted from VFP OleDb query, you could do this for your date column
STUFF( STUFF( DTOS( ct_date ), 5, 0, "-"), 8, 0, "-" )
The VFP Function DTOS will convert a date (or datetime) to a string and will always be in the format of YYYYMMDD. The STUFF command will do the inserting of the hyphen character to properly set to YYYY-MM-DD for you.
You could simply use ToString("yyyy-MM-dd") but better do not even do that. You could directly connect to MySQL and insert data into it using VFP commands and call that via an ExecScript. Or you could directly import from VFP within MySQL connection (I don't use MySQL but you can do that with other databases like MS SQL Server, postgreSQL etc so I assume MySQL is also capable doing that).
Yet another alternative would be to use an XML format to import/export which is much more reliable than plain text.
Yet another way, you could connect to MySQL and VFP, fill MySQL DataTable with your data and submit changes.
IOW using a text file in between would be my last suggestion.
PS: Have a look at FileHelpers.
I have retrieved a date from an application and stored it in a DateTime Variable. The format of date is dd/mm/yyyy.
I now want to update a column (with datatype date (yyyy/mm/dd)) in a sql server 2008 database with this date
I have tried the below code, but it's giving me an exception "string was not recognized as valid datetime". Please help to solve this problem.
DateTime date = calExpirydate.SelectedDate;
DateTime date1 = DateTime.ParseExact(date.ToString(), "YYYY/MM/DD", CultureInfo.InvariantCulture);
You don't need to convert it at all if you use parameters (and you should be).
A rough example:
DateTime date = DateTime.Now;
SqlCommand command = new SqlCommand();
command.CommandText = "INSERT INTO table (date) VALUES (#date)";
command.Parameters.Add("#date",SqlDbType.DateTime).Value = date;
I'm using SQL Server here, however the concept is similar across most ADO.NET providers.
Your DateTime variable in the framework is stored in one basic format. The way it appears is just formatting off of the .ToString. It's saying give me your date bit make it look like this. Sql server is similar, it understands the date time variable regardless of how it appears.
If you pass your DateTime as exactly how it is in the framework it will save it correctly. The date and time isn't changing just how it's displayed. Your try parse isn't working though because it's not able to recognize the partial string you're giving it.
You don't even need a new date time variable to see it the way you want. Even if you're successful you will have identical date time variables.
yyyy/MM/dd should be correct
DateTime string format
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.
What's wrong with this code?
Client c = new Client();
string format = "yyyy/MM/dd HH:mm:ss";
string dateAdded = now.ToString(format);
c.RegistrationDate = DateTime.Parse(dateAdded);
c.RegistrationDate is a dateTime object in the client class and I want it to insert to my database.
However It doesn't convert the freaking date to the format in my mysql database. It always says that string format is incorrect. WHAT have i done wrong???? should I convert my Registration Date to string??? Thanks
**EDIT: Sorry I've forgot to mention. "now" is now = DateTime.Now; it gets the current time of the date and time.
A DateTime doesnt have a format - it's just the date/time. (Whether it's local time, UTC or whatever is a different matter, mind you.)
Firstly, you shouldn't be converting to and from text like you are: that's just a recipe for trouble. Just use:
c.RegistrationDate = now;
... performing any rounding you need to.
You haven't shown how you're trying to insert the value into your database. If you're including the value in the SQL statement directly, that would explain it. You should be using a parameterized SQL statement and passing the value directly in the parameter - no conversion necessary.
If you're already doing that, please show us the code you're trying to use to insert the data, and we'll see what we can do. See the documentation for some examples.
I don't think there is anything wrong with the c# code,except I assume you must be doing
string dateAdded = DateTime.Now.ToString(format);
Otherwise I am not sure what 'now' is.