简体   繁体   English

为什么DateTime.Now在asp.net c#中保存到SQL YYYY-DD-MM?

[英]Why DateTime.Now save to SQL YYYY-DD-MM in asp.net c#?

I tried save DateTime.Now to SQL but column data created like this 我尝试将DateTime.Now保存到SQL,但是像这样创建的列数据

2014-06-02 22:30:19.000

But I want it to be like 但我希望它像

2014-02-06 22:30:19.000

or 要么

06-02-2014 22:30:19.000

My codes: 我的代码:

conn.Open();
var commandSQL= new SqlCommand(@"INSERT INTO TableName(SaveTime) 
values (@SaveTime) ", conn);
commandSQL.Parameters.AddWithValue("SaveTime",DateTime.Now.ToString());   
commandSQL.ExecuteNonQuery();

DateTime in .Net framework and SQL Server doesn't have any format. .Net框架和SQL Server中的DateTime没有任何格式。 You should add the DateTime object directly instead of calling ToString 您应该直接添加DateTime对象,而不是调用ToString

Just remove the ToString when adding value with parameter 使用参数添加值时只需删除ToString

commandSQL.Parameters.AddWithValue("@SaveTime",DateTime.Now);

(You are missing @ with your parameter, but I don't think that is the issue here) (您的参数缺少@,但是我认为这不是问题所在)

Format is only useful for displaying purpose. 格式仅用于显示目的。

SQL Server is perfectly happy to take a string value for any data type, provided there is an implicit conversion defined from string to that datatype , viz: SQL Server非常乐意接受任何数据类型的字符串值,只要存在从字符串到该数据类型隐式转换 ,即:

SQL Server T-SQL数据类型转换表

So... 所以...

What is the data type of your column SaveTime ? 您的列SaveTime的数据类型是什么?

If it is datetime , smalldatetime , datetime2 or date , it means that you're converting a CLR DateTime to a string, which is then converted to the SQL Server datatype with the precision implicit with that datatype. 如果它是datetimesmalldatetimedatetime2date ,则意味着您要将CLR DateTime转换为字符串,然后将其转换为具有该数据类型隐式精度的SQL Server数据类型。 And, it has not representation until you give it one. 而且,它只有在您给它一个代表后才能代表。 Further, there is a possible loss of precision: the finest precision of the resulting SQL Server value is limited by the implicit precision of the string representation you sent to SQL Server. 此外,可能还会损失精度:最终SQL Server值的最佳精度受到发送到SQL Server的字符串表示形式的隐式精度的限制。

If the column's data type is something else — char , nchar , varchar , nvarchar — it will be stored exactly as the string representation you sent up to SQL Server, with all that implies. 如果该列的数据类型是其他类型,即charncharvarcharnvarchar ,则它将完全按照您发送给SQL Server的字符串表示形式进行存储,这意味着所有内容。 When you convert a C# System.DateTime to a string, the default conversion format used is dependent upon the current value of CultureInfo.CurrentCulture for the thread upon which the conversion is performed. 当您将C# System.DateTime转换为字符串时,使用的默认转换格式取决于执行转换的线程的CultureInfo.CurrentCulture的当前值。

Just add the C# DateTime value directly as the value of the parameter: you don't need to convert it to a string. 只需将C# DateTime值直接添加为该参数的值即可:无需将其转换为字符串。 Let the infrastructure do the work for you. 让基础架构为您完成工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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