[英]Insert Datetime.now from asp.net into sql server
I'm trying to insert 'DateTime.Now' into sql column type of datetime but when insert is done in sql
table date is OK! 我正在尝试将'DateTime.Now'插入日期时间的sql列类型中,但是在
sql
表中完成插入后,日期就可以了! (exp: 2015-02-11) but time is stored as 00:00:00!!! (exp:2015-02-11),但是时间存储为00:00:00 !!! I tried to many alternates.
我尝试了许多替代者。 this is my code:
这是我的代码:
sqlComm.Parameters.Add("@join_date", SqlDbType.Date).Value = DateTime.Now.ToString("yyyy-MM-dd h:m:s");
What am I missing??? 我想念什么???
You're specifying a SqlDbType
of Date
- that doesn't have a time. 您正在指定
Date
的SqlDbType
没有时间。 So when the driver is converting the parameter value into the desired type, it's removing the time part. 因此,当驱动程序将参数值转换为所需的类型时,它将删除时间部分。
You're also converting DateTime.Now
into a string for no obvious reason... and doing so in a way which uses an odd and lossy time format ( h:m:s
, with no AM/PM designator). 您还没有明显的原因
DateTime.Now
转换为字符串...并以一种使用奇数和有损时间格式( h:m:s
,没有AM / PM指示符)的方式进行操作。 If you really did want to convert to a string, it would be better to use HH:mm:ss
for the time specifier. 如果你真的想转换为字符串,这将是更好地使用
HH:mm:ss
的时间指定。
This line: 这行:
sqlComm.Parameters.Add("@join_date", SqlDbType.Date).Value = DateTime.Now.ToString("yyyy-MM-dd h:m:s");
should be: 应该:
sqlComm.Parameters.Add("@join_date", SqlDbType.DateTime).Value = DateTime.Now;
Jon's answer is fine, but also, you can make things easier like this: 乔恩(Jon)的回答很好,但是您也可以像下面这样使事情变得简单:
sqlComm.Parameters.AddWithValue("@join_date", DateTime.Now);
It will automatically use the correct data type, based on the type of the value. 它将根据值的类型自动使用正确的数据类型。
Also - You said you were calling this from ASP.Net. 另外-您说您是从ASP.Net调用此功能的。 In web applications,
DateTime.Now
is usually not appropriate - because it uses the time zone of the server , and it doesn't retain any offset information so it can be ambiguous during daylight saving time fall-back transitions. 在Web应用程序中,
DateTime.Now
通常是不合适的-因为它使用服务器的时区,并且它不保留任何偏移量信息,因此在夏令时回退过渡期间可能不明确。 I recommend storing UTC-based values in the database ( DateTime.UtcNow
). 我建议将基于UTC的值存储在数据库中(
DateTime.UtcNow
)。
If you feel that the server's local time zone is relevant in your use case, then consider switching your database column to the datetimeoffset
type and using DateTimeOffset.Now
. 如果您认为服务器的本地时区与您的用例相关,请考虑将数据库列切换为
datetimeoffset
类型并使用DateTimeOffset.Now
。 That will avoid problems with DST transitions. 这样可以避免DST过渡的问题。
See also: The case against DateTime.Now 另请参阅: 针对DateTime.Now的案例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.