Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 2008 数据库日期插入有时有效_Sql Server 2008_C# 3.0_Asp.net 3.5 - Fatal编程技术网

Sql server 2008 数据库日期插入有时有效

Sql server 2008 数据库日期插入有时有效,sql-server-2008,c#-3.0,asp.net-3.5,Sql Server 2008,C# 3.0,Asp.net 3.5,我有以下几行: command.Parameters.Add("@date", SqlDbType.DateTime, 8).Value = date_of_trip; 其中,行程日期是一个字符串,包含25-9-2013(即日-月-年) 这会给我一条错误消息: System.ArgumentException:无法将2013年9月25日转换为System.DateTime。 参数名称:类型-->System.FormatException:未指定字符串 被识别为有效的日期时间 但是,如果行程的

我有以下几行:

command.Parameters.Add("@date", SqlDbType.DateTime, 8).Value = date_of_trip;
其中,
行程日期
是一个字符串,包含
25-9-2013
(即日-月-年)

这会给我一条错误消息:

System.ArgumentException:无法将2013年9月25日转换为System.DateTime。 参数名称:类型-->System.FormatException:未指定字符串 被识别为有效的日期时间


但是,如果行程的日期是2013年1月1日,那么它似乎工作得很好

我猜这是因为服务器希望第一个参数是一个月。尝试使用实时日期时间或yyyy-mm-dd格式(即2013-09-25),该格式应始终有效。

在将字符串发送到数据库之前,应将其解析为
DateTime

例如:

DateTime dt;
if(DateTime.TryParse(date_of_trip, out dt))
{
    command.Parameters.Add("@date", SqlDbType.DateTime, 8).Value = dt;
    // ...
}
else
{
    // you should use a CompareValidator to check if it's a valid date
}
如果要确保即使服务器的当前区域性发生更改,您的给定格式也能正常工作,您可以使用
DateTime.TryParseExact
格式
“dd-MM-yyyy”


对于您的
TryParseExact
示例,我得到的
名称“DateTimeStyles”在当前上下文中不存在
?在
System.Globalization
名称空间中,添加using或write
System.Globalization.DateTimeStyles.None
(编辑答案)。完成,但我现在得到了与'System.DateTime.TryParseExact(string,string[],System.IFormatProvider,System.Globalization.DateTimeStyles,out System.DateTime)“”具有一些无效参数。我使用的是自.NET 2以来存在的参数。请注意,行程的
date\u
是一个
字符串
dt
是一个
DateTime
变量(请参见我的第一个代码示例)。
if (DateTime.TryParseExact(date_of_trip, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt))
{
    // ...
}