Set an empty DateTime variable

2020-02-26 13:47发布

I would declare an empty String variable like this:

    string myString = string.Empty;

Is there an equivalent for a 'DateTime' variable ?

Update :

The problem is I use this 'DateTime' as a parameter for a 'StoredProcedure' in SQL. E.g:

    DateTime? someDate = null;
    myCommand.Parameters.AddWithValue("@SurgeryDate", someDate);

When I run this code an exception is catched telling me the 'StoredProcedure' expected a '@SurgeryDate' parameter. But i provided it. Any idea why?

标签: c# sql datetime
12条回答
【Aperson】
2楼-- · 2020-02-26 14:13

If you set the date to

DateTime dNewDate = new DateTime();

The value is set to {1/1/0001 12:00:00 AM}

查看更多
▲ chillily
3楼-- · 2020-02-26 14:14

The method you used (AddWithValue) doesn't convert null values to database nulls. You should use DBNull.Value instead:

myCommand.Parameters.AddWithValue(
    "@SurgeryDate", 
    someDate == null ? DBNull.Value : (object)someDate
);

This will pass the someDate value if it is not null, or DBNull.Value otherwise. In this case correct value will be passed to the database.

查看更多
Anthone
4楼-- · 2020-02-26 14:19

This will work for null able dateTime parameter

. .

SearchUsingDate(DateTime? StartDate, DateTime? EndDate){
     DateTime LastDate;
     if (EndDate != null)
       {
          LastDate = (DateTime)EndDate;
          LastDate = LastDate.AddDays(1);
          EndDate = LastDate;
        }
}
查看更多
淡お忘
5楼-- · 2020-02-26 14:22

Since DateTime is a value type you cannot assign null to it, but exactly for these cases (absence of a value) Nullable<T> was introduced - use a nullable DateTime instead:

DateTime? myTime = null;
查看更多
戒情不戒烟
6楼-- · 2020-02-26 14:25

Option 1: Use a nullable DateTime?

Option 2: Use DateTime.MinValue

Personally, I'd prefer option 1.

查看更多
该账号已被封号
7楼-- · 2020-02-26 14:28

The .addwithvalue needs dbnull. You could do something like this:

DateTime? someDate = null;
//...
if (someDate == null)
    myCommand.Parameters.AddWithValue("@SurgeryDate", DBnull.value);

or use a method extension...

  public static class Extensions
    {
        public static SqlParameter AddWithNullValue(this SqlParameterCollection collection, string parameterName, object value)
        {
            if (value == null)
                return collection.AddWithValue(parameterName, DBNull.Value);
            else
                return collection.AddWithValue(parameterName, value);
        }
    }
查看更多
登录 后发表回答