.NET 中处理空日期的标准方法是什么

发布于 2024-10-22 07:25:18 字数 895 浏览 2 评论 0原文

我有使用 C# 的 asp.net 表单,我在哪里使用 Linq 像往常一样将用户信息插入到数据库中。出色地。当我也从用户那里获取出生日期时,但是如果用户跳过从用户界面填写日期文本框,那么我会得到像“01/01/0001”这样的日期,这当然是数据库安全不允许的存储它。

所以我需要检查代码中的某个位置它是否为空或采用这种(上面给定的)格式。如果它为空或格式为“01/01/0001”那么我到底需要做什么?我没有任何默认设置 日期的值。

那么,如果日期为空(但不是强制性的),处理日期的标准方法是什么。请指导我。很多次我在处理各种类型的 null 时发现自己陷入了陷阱。

已编辑 看看我做了什么,似乎它在这里工作。但我不认为这是标准方式:

DateTime? otxtDOB = new DateTime();
                    if (!string.IsNullOrEmpty(DOB))
                    {
                    if (Convert.ToDateTime(DOB) != DateTime.MinValue)
                        {
                        otxtDateOfPurchese = Convert.ToDateTime(Convert.ToDateTime(DOB).ToString("dd-MMM-yyyy"));
                        }
                    else
                    {
                     otxtDOB = null;
                        }

                    }

请确认我这是正确的方式吗?

I have asp.net form with C#, where is I am taking user information to insert in the database as usual by using Linq. well. Where as I am taking Date of birth also from the user, but if user skip to fill date text box from ui, then I am getting date like '01/01/0001' something like this, which certainly database security would not allow to store it.

So I need to check somewhere in my code that it is null or in this (above given) format. If it is null or in format '01/01/0001' then what exactly I have to do? I don't have any default
value for dates.

So what is the standard way to handle if date is null (but not mandatory).Please guide me. So many times I found myself in trap while handling null for various types.

Edited
see what i did seems it working here. but i don't think so this is standard way:

DateTime? otxtDOB = new DateTime();
                    if (!string.IsNullOrEmpty(DOB))
                    {
                    if (Convert.ToDateTime(DOB) != DateTime.MinValue)
                        {
                        otxtDateOfPurchese = Convert.ToDateTime(Convert.ToDateTime(DOB).ToString("dd-MMM-yyyy"));
                        }
                    else
                    {
                     otxtDOB = null;
                        }

                    }

Please confirm me is this right way ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

红颜悴 2024-10-29 07:25:18

如果用户未设置日期属性,则将日期属性设为可为空(即“DateTime?”)应该允许它实际上为空。 (如果您的数据库列允许空值,则它可以在数据库中存储为空值)

否则它将默认为 DateTime.MinValue ,这就是您在此处看到的内容。添加到数据库时,您必须明确测试 DateTime.MinValue

Making the date property Nullable (i.e. a "DateTime?") should allow it to actually be null if the user hasn't set it. (And provided your database column will allow nulls, it can be stored as null in the database)

Otherwise it's going to default to DateTime.MinValue which is what you're seeing here. And you'll have to explicity test for DateTime.MinValue when adding to the database.

晨曦÷微暖 2024-10-29 07:25:18

DateTime 是一种值类型(如数字),因此您不能为其分配 null 值。 Mane 人们使用 DateTime.MinValue 或 DateTime.MaxValue 代替,但我更喜欢使用可空类型:

DateTime? nullableDate;
dateSample.Value = null;

DateTime is a value type (like a number), so you can't assing a null value to it. Mane people use DateTime.MinValue or DateTime.MaxValue instead, but I prefer to use nullable types:

DateTime? nullableDate;
dateSample.Value = null;
尝蛊 2024-10-29 07:25:18

你可以做一些像这样的事情 C# 有一些功能,比如可以使用 null 类型
这将为您节省一些代码,并且也更加健壮。

Public int InsertData(int? ouId)
{

chkValue = ouId.HasValue ? ouId.Value : 0;
} 

you can do some thing like this C# have some features like nullable type you can make use of
this it will save you some piece of code it will be more robust too.

Public int InsertData(int? ouId)
{

chkValue = ouId.HasValue ? ouId.Value : 0;
} 
人间不值得 2024-10-29 07:25:18

您可以选择使用Nullable(别名DateTime?)。这使您能够在整个应用程序中将日期处理为空。

但是,就我个人而言,我并没有发现可以为 null 的值,并且更喜欢第二条路径:您可以使用 DateTime.MinValue (即 01/01/0001)作为应用程序中有意义的常量,并检查数据访问层中的 DateTime.MinValue。

如果数据库是 SQL Server 并且字段类型为smalldatetime,则如果您尝试保存DateTime.MinValue,数据库将会溢出并引发异常。然而,Null 很可能以任何类型存储在数据库中。

这是将字符串解析为可为空类型的方法:

private delegate bool TryParseDelegate<T>(string s, out T t);
private static T? TryParseNullable<T>(string s, TryParseDelegate<T> tryParse) where T : struct
{
   if (string.IsNullOrEmpty(s))
       return null;
   T t;
   if(tryParse(s, out t))
      return t;
   return null;
}

使用:

var nullableDateTime = TryParseNullable<DateTime>("01/01/0001", DateTime.TryParse);

You have the option of using Nullable<DateTime> (alias DateTime?). This makes you able to handle the date as null throughout your application.

However, personally I am not to found of nullables and would prefer this second path: You can use DateTime.MinValue (which is 01/01/0001) as a meaningful constant in your application and the check for DateTime.MinValue in your data access layer.

The database, if it is an SQL Server and the field is of type smalldatetime, would overflow and throw an exception if you tried to save DateTime.MinValue. Null however, may well be stored in the database for any type.

This is how you can parse your strings into nullable types:

private delegate bool TryParseDelegate<T>(string s, out T t);
private static T? TryParseNullable<T>(string s, TryParseDelegate<T> tryParse) where T : struct
{
   if (string.IsNullOrEmpty(s))
       return null;
   T t;
   if(tryParse(s, out t))
      return t;
   return null;
}

with usage:

var nullableDateTime = TryParseNullable<DateTime>("01/01/0001", DateTime.TryParse);
友谊不毕业 2024-10-29 07:25:18

使用

DateTime dt; 
if(DateTime.TryParse(DatetImeValue.Tostring(),dt))   // datetimevalue is your db value
{
     datetimeproperty = dt;   // in your class declare it as DateTime? datetimeproperty 
}
else
{
    datetimeproperty = null;
}

显示时检查是否为空,如果其为空则将其设置为空。

[更新]

做一件事,保持属性可为空。在你的数据库中。将字段设置为允许 null 并在参数 user @DateTimeParam = null 中。

或者快速解决方法使数据库字段和参数 VARCHAR 代替 DATETIME,在参数中传递 DATETIMEVALUE.TOSHORTDATESTRING() 并同时检查 IF USER跳过
将 STRING.EMPTY 放入参数中。通过这种方式,您可以轻松显示日期和时间。如果您不需要,则无需铸造或擦掉时间部分

use

DateTime dt; 
if(DateTime.TryParse(DatetImeValue.Tostring(),dt))   // datetimevalue is your db value
{
     datetimeproperty = dt;   // in your class declare it as DateTime? datetimeproperty 
}
else
{
    datetimeproperty = null;
}

While displaying check for null, if its null set it empty.

[Update]

Do one thing, Keep the property nullable. In your database. Set field to allow null and in the parameter user @DateTimeParam = null.

OR A QUICK WORKAROUND MAKE THE DATABASE FIELD AND PARAMETER VARCHAR INSTEAD OF DATETIME, IN PARAMETER PASS DATETIMEVALUE.TOSHORTDATESTRING() AND ALSO CHECK IF USER SKIPS
PUT STRING.EMPTY IN PARAMETER. IN THIS MANNER IT WILL BE EASY TO YOU TO DISPLAY DATE AND TIME. YOU NEED NOT CAST OR WIPE OFF THE TIME PART IF YOU DO NOT NEED IT

入画浅相思 2024-10-29 07:25:18
obj.BirthDate = Convert.ToDateTime(string.IsNullOrEmpty(txtBirthDate.Text.ToString()) ? System.Data.SqlTypes.SqlDateTime.MinValue.Value : Convert.ToDateTime(txtBirthDate.Text.ToString()));
obj.BirthDate = Convert.ToDateTime(string.IsNullOrEmpty(txtBirthDate.Text.ToString()) ? System.Data.SqlTypes.SqlDateTime.MinValue.Value : Convert.ToDateTime(txtBirthDate.Text.ToString()));
八巷 2024-10-29 07:25:18

您可以在传递到数据库时使用它。

object datetimeObj = null;
if (datetimefromUI == DateTime.MinValue) // This is put in the DateTime object by default
    datetimeObj = DBNull.Value;
else
    datetimeObj = datetimefromUI;

// Post datetimeObj to parameter in database...

You can use this while passing to database.

object datetimeObj = null;
if (datetimefromUI == DateTime.MinValue) // This is put in the DateTime object by default
    datetimeObj = DBNull.Value;
else
    datetimeObj = datetimefromUI;

// Post datetimeObj to parameter in database...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文