Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

c# - DateTime doesn't write correctly to database

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...