Inserting Date and time from two text boxes - c#

Inserting Date and Time from two separate Text Boxes. and concatenating for save to database.
I have seen lots of examples for datetime conversions but didn't get any clue.
advance in thanks
DateTime Datetime = Dateconversion.ConvertToDate(txtDate.Text.Trim());
DateTime time = Convert.ToDateTime(txtTime.Text);
insert into table(date) values('"+Datetime+" "+time+"')

First, never use Convert.ToDateTime directly on user input, since it's going to throw exceptions when the input is not convertible to datetime.
Instead, use DateTime.TryParse or DateTime.TryParseExact.
Second, never concatenate strings to create an sql statement, since it's an open door for sql injections attacks. Use parameterized queries instead.
Your code should look something like this:
DateTime DateTimeValue;
string DateTimeString = txtDate.Text.Trim() +' '+ txtTime.Text.Trim();
if(DateTime.TryParse(DateTimeString, out DateTimeValue))
{
using(SqlConnection con = new SqlConnection("ConnectionString")) {
SqlCommand cmd = new SqlCommand("insert into table(date) values(#Value)", con);
cmd.Parameters.Add("#Value", SqlDbType.DateTime).value = DateTimeValue;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}

I will suggest you to concatenate the strings before converting it to date time object.
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
Hope it will help.Please use TryParseExact, do not directly convert user input to date time, can cause serious issues.

Related

Mysql DB returns wrong date format (C#)

This is a very simple question about a confusing circumstance with my C#-App:
Usings:
C# Desktop-App / Mysql 5.5
Whats going on:
My app is selection some data from the db (Select date from mytable). The format for column date is yyyy-mm-dd. After retrieving the data inside my C#-App im getting a culture-sensitive output. In my case in format dd.mm.yyyy. Check out my screenshot from debugging.
Notice: The var listDate is from type string!
My output looks like from type DateTime. But I've never converted it into dateTime. The column(db) date is set to format date.
So why am I getting this format? Is it a db or app problem?
My goal is to get the same format yyyy-mm-dd as inside the db.
Every help appreciated. Thanks very much!!!
EDIT 1:
My code:
public static void DB_Select(string s, params List<string>[] lists)
{
try
{
using(var conn = new MySqlConnection(ServerConnection))
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
using(var sqlreader = cmd.ExecuteReader())
while (sqlreader.Read())
{
if (sqlreader[0].ToString().Length > 0)
{
for (int i = 0; i < lists.Count(); i++)
{
lists[i].Add(sqlreader[i].ToString());
}
}
else
{
foreach (List<string> save in lists)
{
save.Add("/");
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error while selecting data from database!\nDetails: " + ex);
}
}
Cant imagine this could be the problem. All this is doing is looping through the output and saving the single columns into different passed lists (params List<string>[])
Using:
Services.DB_Select("SELECT date FROM myTable WHERE something = something")
So everything is kept into strings without any converts. It is only about the select and the output db -> c#. Im selecting a date-format and getting a dateTime value culture-sensitive. How is this possible?
EDIT 2: (SOLUTION)
If I get it like SELECT CONCAT(date) FROM mytable... (telling the db to handle (col)date as a string I get the clean output yyyy-mm-dd !
Without concat I get my dateTime output culture-sensitive. So it has to be a problem with my date-format for the date column. But why - really dont know.
If you want, you can get it like this:
string example = "20.08.2013 00:00:00";
DateTime result = GetDate(example);
By using this method:
public static DateTime GetDate(string stringFormat)
{
var date = stringFormat.Split(' ')[0].Split('.').Select(x => Int32.Parse(x)).ToArray();
return new DateTime(date[2], date[1], date[0]);
}
Since you did not provide how you get the data from DB it's hard to say. There are probably two options - 1) some kind of implicit conversion done when retrieving data, so you get the formatted string from db or 2) you do the conversion somewhere after you get the data.
What you could do is conversion to DateTime
listDate.Select(d => DateTime.ParseExact(d,"dd.MM.yyyy hh:mm:ss",CultureInfo.InvariantCulture)) and then format it back to format that you need.
Better solution would of course be getting the date in DateTime directly from DB. Please post your code for this.
EDIT
The problem there is that sqlreader[i].ToString() - this takes your Culture from Environment and does the conversion. In that case I would check for type of the value and if that is DateTime then use ToString("yyyy-MM-dd") instead of simple ToString()
From documentation:
This method uses formatting information derived from the current
culture. In particular, it combines the custom format strings returned
by the ShortDatePattern and LongTimePattern properties of the
DateTimeFormatInfo object returned by the
Thread.CurrentThread.CurrentCulture.DateTimeFormat property. For more
information, see CultureInfo.CurrentCulture. Other overloads of the
ToString method enable you to specify the culture whose formatting to
use and to define the output pattern of the DateTime value.
Alright, a college of mine told me a solution. At least it sounds logic to me:
The col itself is from type date which is a short version of dateTime. When using a clear select like SELECT date FROM mytable the output will come as a DateTime. Thats why I also get the time-part inside my output.
When going for SELECT CONCAT(date) FROM mytable the value is handled like a string. A workaround I found myself. This will only output the date itself.
Strange behaviour. For sure because I work with this date-formatted-column for a long time. Never had any problems with it.
Thanks a lot for your interest!

Which SQL Date format

Which date format does T-SQL use? Does it rely on the system date? How can I be sure that my parameters are passed on correctly regardless of system date format. This question comes because of error:
Error converting data type nvarchar to datetime.
The SQL script in part:
CREATE PROCEDURE [dbo].[sz_pipeline04_pipelUpdte_inventory]
-- Add the parameters for the stored procedure here
#myFixDte datetime,
#doInsert bit
AS
BEGIN
The calling c# code:
public static DataTable GridInventory(string strdProcedureName, DateTime fixDate, bool execInsertYN)
{
DataTable dtbl_inventory = null;
try
{
dtbl_inventory = new DataTable();
using (var conn = new SqlConnection(cls_connRegistry.GetConnStrFull()))
using (var command = new SqlCommand(strdProcedureName, conn)
{
CommandType = CommandType.StoredProcedure
})
{
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = DateTime.Parse(fixDate.ToShortDateString());
command.Parameters.Add("#doInsert", SqlDbType.Bit).Value = execInsertYN;
conn.Open();
SqlDataReader dr = command.ExecuteReader();
dtbl_inventory.Load(dr);
conn.Close();
}
}
catch (Exception datawalile)
{ dtbl_inventory = null; }
return dtbl_inventory;
}
edited question.
The code you've now posted looks correct - except for one thing:
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = DateTime.Parse(fixDate.ToShortDateString());
As I've said in the comments, issues only come up around formatting when you convert to strings. So just do:
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = fixDate;
DateTimes (C#) and datetime (T-SQL) don't have a format. You get formatting issues when you convert them into strings. In their native representation, they're usually just a count of a number of events (ticks, milliseconds, etc) since some fixed point in the past. ADO.Net knows how to convert a DateTime into a SQL Server datetime.
If you have remaining conversion issues, it's in code you've not yet shown. But it will, again, be because you're converting away from the correct data type (datetime) and using strings.
This is not valid DATETIME format DD-MM-YYYY.
You can use CONVERT It in following:
DECLARE #myFixDte DATETIME
SET #myFixDte = CONVERT(DATE, N'30-12-2012', 104)
SELECT #myFixDte
Or you can SET It without converting in other format like YYYY-MM-DD
Try this:
#myFixDte = convert(datetime, '30-12-2012', 105)
And check the link provided by #N.Molderf
SQL Server recognizes one format always in same way, regardless which culture it using, and that format is YYYYMMDD.
So you can always use your dates in format 20120202 or 20151225, and SQL Server will parse that parameter using same mask.
Why you didnt tell as above c# datetime, here is a simple example for you how to solve this problem in your case it will be something like this
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("dd-MM-yyyy HH:mm:ss");
or this one
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
second one is a default

Conversion failed when converting date and /or time from character string

Error is appearing in date_to and date_from while adding data into the database.
In sql server database the data type for date_to & date_from are date. suggest some solution.
try
{
cmd = new SqlCommand("insert into license1 values(#l_id,#customer_id,#d_id,#device_name,#from,#to)", cn);
cmd.Parameters.AddWithValue("#l_id", license_id.Text);
cmd.Parameters.AddWithValue("#customer_id", c_comboBox4.Text);
cmd.Parameters.AddWithValue("#d_id", d_id_comboBox4.Text);
cmd.Parameters.AddWithValue("#device_name", d_name_comboBox5.Text);
cmd.Parameters.AddWithValue("#to", date_to.Text);
cmd.Parameters.AddWithValue("#from", date_from.Text);
cn.Open();
a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("Data Submitted");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Take the conversion into your own hands:
cmd.Parameters.AddWithValue("#to", DateTime.Parse( date_to.Text));
cmd.Parameters.AddWithValue("#from", DateTime.Parse( date_from.Text));
and when that still fails, use a version of DateTime.ParseExact() with an appropriate Format and CultureInfo.
You might want to consider adding a more robust and extensive validation layer. Dates and numbers are very sensitive to typing errors, User settings and User assumptions.
Always assume TextBox.Text is full of errors.
if user enters the Date Format as: yyyy-MM-dd then try this:
String strDateFormat= "yyyy-MM-dd";//change accordingly if format is something different
DateTime to=DateTime.ParseExact(date_to.Text,strDateFormat, CultureInfo.InvariantCulture);
DateTime from=DateTime.ParseExact(date_from.Text, strDateFormat, CultureInfo.InvariantCulture);
cmd.Parameters.AddWithValue("#to", to);
cmd.Parameters.AddWithValue("#from", from);
try this
cmd.Parameters.AddWithValue("#to",Convert.ToDateTime(date_to.Text));
cmd.Parameters.AddWithValue("#from",Convert.ToDateTime( date_from.Text});
I think your date format may caused the issue. You must use date format supported by the SQL provider. Most SQL uses MM-dd-yyyy format. So if you pass 21-1-2014, SQL server don't accept it because 21st month don't exist.
If the problem persists while executing your code, perhaps it is due to two important reasons:
You have used the DateTime.Now.ToShortString or similar auto conversion method, and
You changed the computers default Datetime format in the setting.
Change the Datetime format of the computer or change the autoconversion to 'parse' method.

Problems by inserting values from textboxes

I'm trying to insert the current date to the database and i allways get the message(when i press the button on the form to save to my access database), that the data type is incorect in the conditional expression.
the code:
string conString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\Simon\\Desktop\\save.mdb";
OleDbConnection empConnection = new OleDbConnection(conString);
string insertStatement = "INSERT INTO obroki_save "
+ "([ID_uporabnika],[ID_zivila],[skupaj_kalorij]) "
+ "VALUES (#ID_uporabnika,#ID_zivila,#skupaj_kalorij)";
OleDbCommand insertCommand = new OleDbCommand(insertStatement, empConnection);
insertCommand.Parameters.Add("#ID_uporabnika", OleDbType.Char).Value = users.iDTextBox.Text;
insertCommand.Parameters.Add("#ID_zivila", OleDbType.Char).Value = iDTextBox.Text;
insertCommand.Parameters.Add("#skupaj_kalorij", OleDbType.Char).Value = textBox1.Text;
empConnection.Open();
try
{
int count = insertCommand.ExecuteNonQuery();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
empConnection.Close();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
}
I have now cut out the date,( i made access paste the date ), still there is the same problem. Is the first line ok? users.idtextbox.text?
Please help !
try Changing
insertCommand.Parameters.Add("#datum", OleDbType.Char).Value = DateTime.Now;
to
`insertCommand.Parameters.Add("#datum", OleDbType.Char).Value
= DateTime.Now.ToString("dd MMM yyyy HH:mm");`
( or some other acceptable date format)
Assuming that your database actually holds dates, and not strings, for the date column - I think you're trying to insert char values into your date column.
Change
insertCommand.Parameters.Add("#datum", OleDbType.Char).Value = DateTime.Now;
to
insertCommand.Parameters.Add("#datum", OleDbType.Date).Value = DateTime.Now;
I think you are getting issue due to the date format set in your regional settings and the date format accepted by MS Access.
You can use a specific date format as mentioned in following code.
DateTimeFormatInfo ukDTFomat = new CultureInfo("en-GB", false).DateTimeFormat;
DateTime.Now.ToString("yyyy-MM-dd", ukDTFomat);
You can simplify your OleDb usage by adding parameters like this:
OleDbParameter param = new OleDbParameter("#datum", DateTime.Now);
command.Parameters.Add(param);
This uses the override of the OleDbParameter that takes a string (the parameter name) and an object (whatever the value should be for the parameter). This lets OleDb figure out the correct parameter type for you (and saves you a lot of work typing and changing parameter types).
Update: just noticed this is Jet. All bets are off when it comes to Access, so I'm by no means sure the above will work.
You should use the type OleDbType.Date in the parameter. That maps to a DateTime value in .NET and an OLE date (internally represented as double) in the database. That's what Access uses for storing dates.
With any of the other date formats in OleDbType, it will be converted to a string representation that Access doesn't recognise as a date.
If you use OleDbType.Char the DateTime value will be converted to a string using the current culture in .NET, which may or may not be understood by Access depending on what the culture happens to be. In your case it seems that it was not understood.
Are you sure the problem is the date value? I.e., are the other columns really of type Char? For date values, you should use OleDbType.DBDate but you should also use the appropriate type for the other columns.
EDIT
Tested against an Access database with a date column, the following worked (although stripped the time obviously):
cmd.Parameters.Add( "#DateColumn", OleDbType.DBDate ).Value = DateTime.Now;
As well as (which included the time)
cmd.Parameters.Add( "#TestDate", OleDbType.Date ).Value = DateTime.Now;
EDIT As with the date parameters, you should be passing specific types for the other values:
insertCommand.Parameters.Add("#ID_uporabnika", OleDbType.Integer).Value = int.Parse( users.iDTextBox.Text );
insertCommand.Parameters.Add("#ID_zivila", OleDbType.Integer.Value = int.Parse( iDTextBox.Text );
insertCommand.Parameters.Add("#skupaj_kalorij", OleDbType.Integer).Value = int.Parse( textBox1.Text );

No milliseconds value when reading DateTime values from a SQL database in C#

I have high precision dates stored in an SQL server, e.g.
2009-09-15 19:43:43.910
However when I convert that value into a DateTime the miliseconds value of the resulting DateTime value is 0:
reader["Timestamp"] = 15/09/2009 19:43:43.000
Having these DateTime values in precision down to milliseconds is very important to me - what is the best way of doing this?
UPDATE: This is the code that performs the conversion:
DateTime myDate = (DateTime)reader[Timestamp"];
There is nothing special about the SELECT statement, in fact it is a SELECT * - no fancy casts or anything
It appears that the DateTime object returned by the SqlDataReader simply is not populated with the Millisecond value
I had this same problem and after some reading it turns out that when you retrieve the date as you were doing
DateTime myDate = (DateTime)reader["Timestamp"];
the SQLDataReader drops the milliseconds. However if you use the GetDateTime method of the SQLDataReader it returns a DateTime object which preserves the milliseconds:
reader.GetDateTime(reader.GetOrdinal("Timestamp"));
Maybe this (Difference between DateTime in c# and DateTime in SQL server) will help a little.
That is because the default format string for DateTime doesn't include milliseconds.
If you use a custom format, you will see the milliseconds value.
An example:
public class Program
{
private static string connString = #"Data Source=(local);Initial Catalog=DBTest;Integrated Security=SSPI;";
public static void Main(string[] args)
{
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM MilliSeconds"))
{
cmd.Connection = conn;
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
DateTime dt = (DateTime)reader["TimeCollected"];
int milliSeconds = dt.Millisecond;
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss.fff"));
}
}
}
Console.ReadLine();
}
}
From a database with these values:
1 2009-09-22 18:11:12.057
2 2009-09-22 18:11:28.587
3 2009-09-22 18:11:29.820
The resulting output from the code above is:
2009-09-22 18:11:12.057
2009-09-22 18:11:28.587
2009-09-22 18:11:29.820
I had the same problem, and I solved it by persisting the C# DateTime as a SQL bigint populated with DateTime.Ticks. This preserves the full DateTime precision. And of course can be de-serialized with the DateTime(long ticks) constructor.
Here's how I'd try to troubleshoot this:
step through in the debugger and look at the type and value of reader[Timestamp"]. If the type is not SqlDateTime, that would make me suspicious-- I'd then look at the query to figure out why that column was returning another type instead of DATETIME (or DATETIME2, etc.)
if that value is SqlDateTime and it does contains milliseconds, then I'd look at the cast as the source of the problem. To validate this, I'd try (in debugger or code) SqlDataReader.GetDateTime() and SqlDataReader.GetSqlDateTime() to see if either returns the correct result. This admittedly seems really unlikely as source of the problem-- casting should work fine.
if that value from #1 is SqlDateTime but contains no milliseconds, then I'd look to an upstream problem in the database-- in other words your query is returning something without milliseconds. when you execute the exact same query in Management Studio, do you see milliseconds?
My guess is this is a query-related issue. But am intrigued to find our more.

Categories