我正在更新一个表格,其中包含不同的值,其中还有一个日期数据类型。
在更新表格之后,我会根据数据类型将变量初始化为0和空格,但我无法初始化Datetime数据类型。
如何用C#实现这个功能?
我正在更新一个表格,其中包含不同的值,其中还有一个日期数据类型。
在更新表格之后,我会根据数据类型将变量初始化为0和空格,但我无法初始化Datetime数据类型。
如何用C#实现这个功能?
DateTime a = default(DateTime);
default(type)
适用于任何类型,不仅限于值类型。 default(string)
将返回null
。 - this. __curious_geek您可以隐式地将值初始化为default(type)
。例如对于DateTime类型:default(DateTime)
。
对于数据库操作,您最好使用SqlDateTime
类型,因为DateTime
的最小或最大值通常无法作为日期类型存储在数据库中。
初始化:
string connString = "...";
string cmdText = @"INSERT INTO Test(col1, col2) VALUES (@col1, @col2)";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.Parameters.Add("@col1", SqlDbType.NVarChar).Value = ""; // or .Value=DBNull.Value;
cmd.Parameters.Add("@col2", SqlDbType.DateTime).SqlValue = default(SqlDateTime); // or .Value=DBNull.Value;
}
}
您可以将所有值初始化为 DBNull.Value
DateTime? datetime;
由于DateTime是一个结构体而不是类,因此当您声明该类型的字段或变量时,您会得到一个DateTime对象而不是引用。同样,就像int不能为null一样,这个DateTime对象永远不可能为null,因为它不是引用。
添加问号将其转换为可空类型,这意味着它既可以是DateTime对象,也可以是null。
最后,在使用该值时,请将该值分配给DateTime:
if(datetime.hasvalue)
{
DateTime dt = datetime.value;
}
这个问题有点老了...但仍然相关。 创建一个新的DateTime变量
DateTime dDate = new DateTime();
将其初始值设为{1/1/0001 12:00:00 AM}...这可能是您想要的。
如果日期超出1753年1月1日至9999年12月31日的范围,MSSQL会给出一个范围错误
datetime TSQL
在数据库数据的情况下...我认为空日期比错误日期更好。
无论如何...初始化日期值的一种方法是:
DateTime dDate = new DateTime(1980,01,01);
关于这个的各种重载:DateTime 结构体