如何在C#.net中为nulltime赋值null值 [英] how to assign null value to datetime in C#.net
问题描述
您好b $ b
如何将null值分配给日期?默认情况下,我的日期时间是 1/1/0001
,但我想将日期时间分配给 null
。如何将null值分配给datetime?
我试过这段代码但是它没有用。
dt = Convert.ToDateTime(strposteddate);
strposteddate = dt.ToShortDateString();
if (strposteddate == 1 / 1/0001)
{
strposteddate = null ;
}
将datetime变量定义为可空:
< pre lang =c#> DateTime? dt = null ;
DateTime
不是可空的类型。您可以使用Nullable< datetime> dt;
嗯,这是可以为空的DateTime
的基本内容。DateTime
struct本身不提供null选项。但是我们可以将它设为可以为空的
类型,它允许你将空值分配给日期时间。
日期时间? nullableDateTime = null ;
if (nullableDateTime.HasValue)
Console.WriteLine(nullableDateTime.Value.ToShortDateString());
因为,我的nullableDateTime设置为Null,上面的代码块不会打印任何东西。
这只会打印一个值,如果nullableDateTime有一些价值。
来到最短的日期,
var defaultDateTimeValue = default (约会时间);
这里defaultDateTimeValu
将是1/1/0001 12: 00:00 AM}
但是,对于nullableType,
var defaultDateTimeValue =默认情况下(的DateTime?);
defaultDateTimeValue
的值应为null
。
我希望这会给你足够的想法。
Hi
How to assign null value to date? By default my datetime is 1/1/0001
, but I want to assign datetime to null
. How can I assign null value to datetime?
I tried by this code but it is not working.
dt = Convert.ToDateTime(strposteddate);
strposteddate = dt.ToShortDateString();
if (strposteddate == "1/1/0001")
{
strposteddate = null;
}
You define the datetime variable as nullable:
DateTime? dt = null;
DateTime
is not nullable type. You can useNullable<datetime> dt;
Well, Here is the fundamental stuff ofnullable DateTime
.DateTime
struct itself does not provide a null option. but we can make it anullable
type which allows you to assign the null to a datetime.
DateTime ? nullableDateTime = null ; if(nullableDateTime.HasValue) Console.WriteLine(nullableDateTime.Value.ToShortDateString());
As, my nullableDateTime is set to Null, above code block wont print anything.
This will only print a value, if the nullableDateTime has some value.
Come to the minimum date,
var defaultDateTimeValue = default(DateTime);
HeredefaultDateTimeValu
will be the1/1/0001 12:00:00 AM}
But, for nullableType,
var defaultDateTimeValue = default(DateTime?);
the value ofdefaultDateTimeValue
should benull
.
I hope this will give you enough idea.
这篇关于如何在C#.net中为nulltime赋值null值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!