How to set DateTime to null

前端 未结 6 1168
半阙折子戏
半阙折子戏 2021-01-31 13:25

Using C#. I have a string dateTimeEnd.

If the string is in right format, I wish to generate a DateTime and assign it to eventCustom.DateTimeEnd

相关标签:
6条回答
  • 2021-01-31 14:10

    It looks like you just want:

    eventCustom.DateTimeEnd = string.IsNullOrWhiteSpace(dateTimeEnd)
        ? (DateTime?) null
        : DateTime.Parse(dateTimeEnd);
    

    Note that this will throw an exception if dateTimeEnd isn't a valid date.

    An alternative would be:

    DateTime validValue;
    eventCustom.DateTimeEnd = DateTime.TryParse(dateTimeEnd, out validValue)
        ? validValue
        : (DateTime?) null;
    

    That will now set the result to null if dateTimeEnd isn't valid. Note that TryParse handles null as an input with no problems.

    0 讨论(0)
  • 2021-01-31 14:11

    You can write DateTime? newdate = null;

    0 讨论(0)
  • 2021-01-31 14:21

    Now, I can't use DateTime?, I am using DBNull.Value for all data types. It works great.

    eventCustom.DateTimeEnd = string.IsNullOrWhiteSpace(dateTimeEnd)
      ? DBNull.Value
      : DateTime.Parse(dateTimeEnd);
    
    0 讨论(0)
  • 2021-01-31 14:22

    This line:

    eventCustom.DateTimeEnd = dateTimeEndResult = true ? (DateTime?)null : dateTimeEndResult;
    

    is same as:

    eventCustom.DateTimeEnd = dateTimeEndResult = (true ? (DateTime?)null : dateTimeEndResult);
    

    because the conditional operator ? has a higher precedence than the assignment operator =. That's why you always get null for eventCustom.DateTimeEnd. (MSDN Ref)

    0 讨论(0)
  • 2021-01-31 14:23

    This should work:

    if (!string.IsNullOrWhiteSpace(dateTimeEnd))
        eventCustom.DateTimeEnd = DateTime.Parse(dateTimeEnd);
    else
        eventCustom.DateTimeEnd = null;
    

    Note that this will throw an exception if the string is not in the correct format.

    0 讨论(0)
  • 2021-01-31 14:25

    DateTime is a non-nullable value type

    DateTime? newdate = null;
    

    You can use a Nullable<DateTime>

    c# Nullable Datetime

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