如何在C#.net中为nulltime赋值null值 [英] how to assign null value to datetime in C#.net

查看:348
本文介绍了如何在C#.net中为nulltime赋值null值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好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 use Nullable<datetime> dt;


Well, Here is the fundamental stuff of nullable DateTime. DateTime struct itself does not provide a null option. but we can make it a nullable 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);


Here defaultDateTimeValu will be the 1/1/0001 12:00:00 AM}
But, for nullableType,

var defaultDateTimeValue = default(DateTime?);


the value of defaultDateTimeValue should be null.

I hope this will give you enough idea.


这篇关于如何在C#.net中为nulltime赋值null值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆