How to set DateTime to null

前端 未结 6 1353
半阙折子戏
半阙折子戏 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.

提交回复
热议问题