Convert a string to smalldatetime - c#

I have a string arranged in a way that would match the format yyyy-dd-MM HH:mm:ss
It might look like this 2010-20-12 13:30:00
I need to insert this into a smalldatetime column in SQL Server. The format of the column is
yyyy-MM-dd HH:mm:ss
I need the string to look like this 2010-12-20 13:30:00 or else SQL Server will get the month and day confused.
Thanks for your thoughts

Don't send your data to SQL server using a string to start with. Instead, use a parameterized SQL statement, and get the driver to do the work for you after you specify a DateTime. (See the SqlCommand.Parameters documentation for an example.)
This is how you should deal with pretty much all values - especially those entered by users. As well as not having to worry about formatting, this will prevent SQL injection attacks.
So that just leaves the task of parsing your input string as a DateTime, which is best done with DateTime.ParseExact or DateTime.TryParseExact, depending on whether you want the result of a parsing failure to be an exception or not.

you can try something like this:
//First convert string to DateTime
DateTime dt;
dt = Convert.ToDateTime("2010-20-12 13:30:00");
//Second Convert DateTime to formatted string
string t_time;
t_time = dt.ToString("yyyy-dd-MM hh:mm tt");
HTH.

You shouldn't need to convert to a string. Use a parameterized sql query or a stored procedure and just provide a datetime object as the parameter. The sql command will handle the insert just fine.
If you only have the string, you can turn it into a datetime using DateTime.Parse and a DateTimeFormatInfo (see this documentation for assistance with creating the format info).

Related

Why C# convert date time format when query from db

When I get data from Mysql table the datetime column 2017-09-19 16:14:47 will automatically convert into its own format like 9/19/2017 3:45:50 PM. It happens when I'm getting data into DataTable and convert into string as follows:
DataTable update;
localdb.MysqlQuery(queryUpdate);
update = localdb.QueryEx();
if (update.Rows.Count > 0)
{
onlinedb = new DataAccessOnline();
foreach (DataRow row in update.Rows)
{
row["added"].ToString(); //9/19/2017 3:45:50 PM
but I need get this value as it is in TABLE column 2017-09-19 16:14:47 how can I do that ?
First you need to convert the data you get from the DB into a DateTime object using the Convert.ToDateTime method.
Then you can specify the format you want on the DateTime.toString method.
It would look something like this:
DateTime added = Convert.ToDateTime(row["added"].ToString());
string formatted = added.toString("yyyy-MM-dd HH:mm:ss");
You can format it in your server side query as string.
mySql is giving data to C# as datetime type. C# has slightly different format of interpreting and presenting datetime type value to you. Ultimately, data will work like a datetime field anyways.
If you bring it like a formatted string, you would need to convert it to datetime in C# to make it function like a datetime. On the other hand, if you want it to be converted in C# for presentation purposes, do it in C#, not while bringing data because then it would be a string, not datetime.
You can see more .ToString() conversion details here.
Default format you need is "u", but you can provide your own format string like this one.
string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

Convert date type in c# to match sql server 2008 date type

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

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.

Cannot pass date into stored procedure

Trying to pass date into a stored procedure as follows:
#dateRegistered = '28/04/2012'
But it keeps telling me:
Error converting data type varchar to date.
It works if I do it as:
#dateRegistered = '04/28/2012'
But this is not the format I want to use.
I have run the following query to set the format:
SET DATEFORMAT dmy
Why isn't it working?
Edit: Here is how I did it:
In my stored procedure, I put:
SET DATEFORMAT dmy
Then from code, I pass it as:
myCommand.Parameters.Add("#dateRegistered", SqlDbType.Date);
myCommand.Parameters["#dateRegistered"].Value = DateTime.Now.ToString("dd/mm/yyyy");
I passed it as string to ensure that even if my computer (or the server) has a different date format, it will always use dmy.
Edit Edit:
I passed it as datetime.now. It seems to transform it to the default format when I send it, and then transform it back to my computer format when I read it. Unsure how exactly this happens, but it seems to be working fine.
It looks like the parameter is a date (in the database), while you try to pass a string (which corresponds to varchar in the database). If you instead pass a .NET DateTime object it should work as expected.
Save yourself the headache and use an unambiguous date format - 20120428 (YYYYMMDD) or 2012-04-28.
As an aside: you mention you're using C# (based on the tags) - how are you using ADO.NET? Or is it Linq to SQL / EF / some other ORM?
Edit:
Ok, use the CONVERT function with an appropriate parameter indicating the format of your date string
EG:
declare #D datetime
set #D = CONVERT(datetime, '04/28/2012', 101)
print #D
101 is US standard format mm/dd/yyyy.
Using convert will ensure it ALWAYS works regardless of any environment settings such as the date order.
If you call set dateformat dmy, that only affects the current connection. You'd have to set it every time right before you convert the string to a date.
The best solution is probably the ISO format, like #IanYates suggests.
dear your code is working after using
* SET DATEFORMAT dmy
because you are passing date as "dd/MM/yyyy"
like "DateTime.Now.ToString("dd/mm/yyyy")"
check the date format in your database by following command :-
dbcc useroptions
and check "dateformat : mdy" by default. So passing your date in "MM/dd/yyyy" format will also work fine.
Happy Coding :)

How to get datetime records in "dd/mm/yyyy h:m:s" format FROM SQL server 2005?

I want to get records from sql server 2005 in datetime format like this "dd/mm/yyyy h:m:s"
My database date is default datetime format
AttLogId int
...
DownloadLog datetime
I am trying to retrieve the datetime like this:
SELECT AttLogId ,convert(varchar,DownloadLogDate,103) FROM AttLog
ORDER BY DownloadLogDate
but I only get the date and not the time.
I suggest you don't try to get the values in a particular string format. Fetch them as DateTime values and then format them in the .NET code using DateTime.ToString("dd/MM/yyyy H:m:s").
It's almost always worth keeping data in its "natural" data type (date/time here) for as long as possible, only converting to text when you really need to. So your SQL should just be:
SELECT AttLogId, DownloadLogDate FROM AttLog
ORDER BY DownloadLogDate
How you then retrieve the data will depend on how you're talking to SQL (e.g. LINQ to SQL, using SqlDbReader etc). But you should be able to get it as a DateTime and then format it locally. This will make it easier to test, easier to debug, give you more control over cultural aspects (date separators, possibly specifying a standard specifier instead of a custom one, etc).
it is because you are using 103 , so it will give only date .
if you want more format check this :
http://msdn.microsoft.com/en-us/library/ms187928.aspx
According to need, u can try this
SELECT AttLogId , convert(varchar(10),DownloadLogDate,103) +' '+ convert(varchar(8),DownloadLogDate,108) FROM AttLog ORDER BY DownloadLogDate
Note : firstone is for date and second one is for time in H:M:S
hope this help u..

Categories