I am trying to save the current date time format from C# and convert it to an SQL Server date format like so yyyy-MM-dd HH:mm:ss
so I can use it for my UP
Your problem is in the "Date" property that truncates DateTime
to date only.
You could put the conversion like this:
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss"); // <- No Date.ToString()!
I think the problem was the two single quotes missing.
This is the sql I run to the MSSMS:
WHERE checktime >= '2019-01-24 15:01:36.000' AND checktime <= '2019-01-25 16:01:36.000'
As you can see there are two single quotes, so your codes must be:
string sqlFormattedDate = "'" + myDateTime.Date.ToString("yyyy-MM-dd") + " " + myDateTime.TimeOfDay.ToString("HH:mm:ss") + "'";
Use single quotes for every string in MSSQL or even in MySQL. I hope this helps.
Let's use the built in SqlDateTime class
new SqlDateTime(DateTime.Now).ToSqlString()
But still need to check for null values. This will throw overflow exception
new SqlDateTime(DateTime.MinValue).ToSqlString()
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
DateTime date1 = new DateTime();
date1 = Convert.ToDateTime(TextBox1.Text);
Label1.Text = (date1.ToLongTimeString()); //11:00 AM
Label2.Text = date1.ToLongDateString(); //Friday, November 1, 2019;
Label3.Text = date1.ToString();
Label4.Text = date1.ToShortDateString();
Label5.Text = date1.ToShortTimeString();
If you wanna update a table with that DateTime, you can use your SQL string like this example:
int fieldId;
DateTime myDateTime = DateTime.Now
string sql = string.Format(@"UPDATE TableName SET DateFieldName='{0}' WHERE FieldID={1}", myDateTime.ToString("yyyy-MM-dd HH:mm:ss"), fieldId.ToString());
Your first code will work by doing this
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss"); //Remove myDateTime.Date part