I'm having a problem with the format of my datetime in a SQL-command. As you can see in the code below, I'm writing some values to my database. As output I'm getting a DD-MM-YYYY-TT:TT:TT
format. This format isn't correctly being written into my database. I'm using a DateTime2 data type into my database.
public partial class ApmStandardLayoutComponent
{
public void WriteTag(string sTagName, string sValue)
{
try
{
string connectionstring = "Data Source=localhost;Initial Catalog=HMI_DB;User ID=sa;Password=sa;";
using (SqlConnection con = new SqlConnection(connectionstring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("", con))
{
//cmd.CommandText = "insert into dbo.CommandQueue values ('" + sTagName + "', '" + sValue + "', 1,'" + DateTime.Now.ToString() + "')";
cmd.CommandText = "insert into dbo.CommandQueue values ('" + sTagName + "', '" + sValue + "', 1,'1-1-2021')";
Console.WriteLine(cmd.CommandText);
cmd.ExecuteNonQuery();
}
con.Close();
}
}
catch (Exception ex)
{
}
}
}
I somehow need to format this code into YYYY-MM-DD-TT:TT:TT
. Can anybody help me how to do this?
One weird thing though, when I'm writing a static date to my database, the format happens correctly. I believe it has something to do with today's or yesterdays date.
question from:
https://stackoverflow.com/questions/65844538/datetime-doesnt-write-correctly-to-database 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…