Set an empty DateTime variable

前端 未结 12 2030
走了就别回头了
走了就别回头了 2020-12-16 08:59

I would declare an empty String variable like this:

    string myString = string.Empty;

Is there an equivalent for a \'DateTime\' variable

相关标签:
12条回答
  • 2020-12-16 09:42

    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);
            }
        }
    
    0 讨论(0)
  • 2020-12-16 09:44

    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.

    0 讨论(0)
  • 2020-12-16 09:45

    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;
    
    0 讨论(0)
  • 2020-12-16 09:45

    If you set the date to

    DateTime dNewDate = new DateTime();
    

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

    0 讨论(0)
  • 2020-12-16 09:47

    You can set a DateTime variable to be '1/1/0001 00:00:00' but the variable itself cannot be null. To get this MinTime use:

    DateTime variableName = DateTime.MinValue;
    
    0 讨论(0)
  • 2020-12-16 09:48

    A string is a sequence of characters. So it makes sense to have an empty string, which is just an empty sequence of characters.

    But DateTime is just a single value, so it's doesn't make sense to talk about an “empty” DateTime.

    If you want to represent the concept of “no value”, that's represented as null in .Net. And if you want to use that with value types, you need to explicitly make them nullable. That means either using Nullable<DateTime>, or the equivalent DateTime?.

    DateTime (just like all value types) also has a default value, that's assigned to uninitialized fields and you can also get it by new DateTime() or default(DateTime). But you probably don't want to use it, since it represents valid date: 1.1.0001 0:00:00.

    0 讨论(0)
提交回复
热议问题