C# DateTime 为空字符串或 null ?如何检查?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8985854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:26:43  来源:igfitidea点击:

DateTime as empty String or null ?How to check?

c#asp.netdatetimereporting-servicesssrs-2008

提问by Anyname Donotcare

Q:

问:

I want to check the DateTime against null valueto empty the cell in my report if the datetime is null.but i don't know how to do this :it appears like this 1/1/0001if it was null.and i want it to be empty cell.

null value如果日期时间为空,我想检查日期时间以清空报告中的1/1/0001单元格。

This is the datatype in my dataset :

这是我的数据集中的数据类型:

enter image description here

在此处输入图片说明

and this is the expression value of my column :

这是我的列的表达式值:

=FormatDateTime(Fields!D_DateTime.Value,2)

采纳答案by Anyname Donotcare

=IIf(FormatDateTime(Fields!D_DateTime.Value,2)=CDate("1/1/0001"),"",FormatDateTime(Fields!D_DateTime.Value,2))

Thanks a lot ,i think this fixes my problem.

非常感谢,我认为这解决了我的问题。

回答by Marco

As I told you in my comment, you should check if your date is DateTime.MinValue(the minimum value a date can assume, which is exactly 01/01/0001).

正如我在评论中告诉你的,你应该检查你的日期是否是DateTime.MinValue(日期可以假设的最小值,也就是 01/01/0001)。

if (your_date_property == DateTime.MinValue)
{
    // Do what you need
}

回答by Maheep

As datetime is a struct rather than class i.e. a value type rather than a reference type; it must be initialized with some value. It cannot have null values.

由于 datetime 是一个结构而不是类,即值类型而不是引用类型;它必须用某个值初始化。它不能有空值。

Hence to check the default value you should check the equality with DateTime.MinValue

因此要检查默认值,您应该检查与 DateTime.MinValue 的相等性

i.e.

IE

if(D_DateTime.Value == DateTime.MinValue)
{
   //write code here for default value handling
}

回答by lc.

Change the type of the field in the dataset (rd:TypeName) to System.Nullable (Of System.DateTime). Then you can simply test =Fields!D_DateTime.Value Is Nothing.

将数据集中的字段类型 ( rd:TypeName) 更改为System.Nullable (Of System.DateTime)。然后你可以简单地测试=Fields!D_DateTime.Value Is Nothing.

回答by LCJ

Like @Marco suggested you can check for MinValue. And if you want to pass NULLto the nullable parameter, you can use the following code for reportviewerparameter.

就像@Marco 建议您可以检查MinValue. 而如果你想传递NULL给可为空的参数,你可以使用下面的reportviewer参数代码。

Vb.Net

网络

Dim rpFrom As New ReportParameter("FromDate", New String() {Nothing}, False)

C#

C#

ReportParameter rpFrom = new ReportParameter("FromDate", new string[] { null }, false);