Search code examples
c#sqlsql-serversql-server-2005splistitem

How to format SQLServer DateTime (mm/dd/yyy HH:MM:SS AM/PM)


Help please.

How can I format the DateTime column in SQLServer 2005 to store the following format: (mm/dd/yyy HH:MM:SS AM/PM)

Below is my code:

        private void UpdateRecord(string status, int approvalid, DateTime modifiedDate)
    {
        SqlConnection conn = new SqlConnection(_strConn);
        SqlCommand cmd = new SqlCommand(@"UPDATE MyLeaveStatusSP SET LeaveStatus = @LeaveStatus, ModifiedDate = @ModifiedDate WHERE ApprovalID = @ApprovalID;", conn);
        cmd.Parameters.Add("@LeaveStatus", SqlDbType.NVarChar, 50).Value = status;
        cmd.Parameters.Add("@ApprovalID", SqlDbType.Int).Value = approvalid;
        cmd.Parameters.Add("@ModifiedDate", SqlDbType.DateTime).Value = modifiedDate;
        cmd.Connection = conn;
        cmd.CommandType = CommandType.Text;

        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception err)
        {
            System.Diagnostics.Debug.WriteLine("ERROR: " + err.Message);
        }
        finally
        {
            conn.Close();
        }
    }

Solution

  • No formatting should be necessary -- SQL should be able to insert the date as-is.

    SQL knows how to save the date; formatting should be done in the UI.

    Now if you're storing the date in a varchar field, that's a different story, to which I would simply respond with: Don't.