简体   繁体   中英

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();
        }
    }

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.

If you really need to then you can either have convert in the .NET and pass the string, or call a stored procedure which receives the date and converts it. Since it doesn't match any of the predefined formats for datetimes, you'll have to roll your own, but this is trivial if cumbersome:

select right('0' + cast(datepart(dd, @dt) as varchar(2)), 2)
 + '/'
 + right('0' + cast(datepart(mm, @dt) as varchar(2)), 2)
 + '/'
 + right(cast(datepart(yyyy, @dt) as varchar(4)), 3) -- are you sure you want yyy and not yyyy?
 + ' '
 + right('0' + cast(datepart(hh, @dt) % 12 as varchar(2)), 2)
 + ':'
 + right('0' + cast(datepart(mi, @dt) as varchar(2)), 2)
 + ':'
 + right('0' + cast(datepart(ss, @dt) as varchar(2)), 2)
 + ' '
 + (case when datepart(hh, @dt) < 12 then 'AM' else 'PM' end)

Still, I'm up-voting LittleBobbyTables' answer, as storing dates as strings in a database is a very bad idea and bound to cause problems. I'm only detailing how to do the conversion in case you are having to deal with someone else's code.

As stated above, you don't set formatting when your saving data... you control it on output. Here are some easy ways to change the formatting on your output using the CONVERT function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM