[英]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) 如何在SQLServer 2005中格式化DateTime列以存储以下格式:(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应该能够按原样插入日期。
SQL knows how to save the date; SQL知道如何保存日期。 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. 现在,如果您将日期存储在
varchar
字段中,那就是另一回事了,我只想回答一下:不要。
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. 如果确实需要,则可以在.NET中进行转换并传递字符串,也可以调用存储过程来接收日期并将其转换。 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. 不过,我还是不赞成LittleBobbyTables的答案,因为将日期作为字符串存储在数据库中是一个非常糟糕的主意,并且肯定会引起问题。 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.
这是一些使用CONVERT函数更改输出格式的简单方法 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.