DateTime format to SQL format using C#

前端 未结 15 1004
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 02:47

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

相关标签:
15条回答
  • 2020-11-28 02:58

    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()!
    
    0 讨论(0)
  • 2020-11-28 02:59

    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.

    0 讨论(0)
  • 2020-11-28 03:02

    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.

    0 讨论(0)
  • 2020-11-28 03:03
       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();
    
    0 讨论(0)
  • 2020-11-28 03:07

    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());
    
    0 讨论(0)
  • 2020-11-28 03:08

    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 
    
    0 讨论(0)
提交回复
热议问题