Nullable DateTimes and the AddDays() extension

前端 未结 4 1135
暗喜
暗喜 2021-01-12 02:34

I have a DateTime variable that can either be null or a Datetime. I figured a nullable DateTime type would work, but I am getting an error telling me that said

相关标签:
4条回答
  • 2021-01-12 02:58

    If you look at the documentation for the Nullable<T> type, you'll see it only has a few members. The Value member will get you the T inside, if the Nullable<T> container has a value. The Nullable<T> doesn't borrow any members from the type T it wraps.

    0 讨论(0)
  • 2021-01-12 03:02

    You need to go through the "Value" property:

    lastInvite.Value.AddDays(7)
    

    Note that this will throw an exception if the DateTime is actually null. Luckily, there is another property you can use to test for this, "HasValue".

    if (lastInvite.HasValue){ /* code */ }
    
    0 讨论(0)
  • 2021-01-12 03:09

    There are multiple ways to resolve this error.

    1. Use Convert.ToDateTime() method which handles null datetime values.

      Convert.ToDateTime(lastInvite).AddDays(7);

    2. Use Value property

      lastInvite.Value.AddDays(7)

    3. Use GetValueOrDefault() method

      lastInvite.GetValueOrDefault().AddDays(7)

    0 讨论(0)
  • 2021-01-12 03:15

    You should consider trying to make your logic more readable:

    var inviteNudgeFlag = bool.Parse((string) Session["InviteNudgeFlag"]);
    
    if(!inviteNudgeFlag)
    {
        return;
    }
    
    var lastInvite = (DateTime?) Session["LastInviteSent"];   
    var inviteCount = (int) Session["InviteCount"];
    var numOfDays = 7;
    var now = DateTime.Now;
    
    var weekSinceLastInvite = lastInvite.HasValue
                                ? now >= lastInvite.Value.AddDays(numOfDays)
                                : now >= AcctCreation.AddDays(numOfDays);
    
    var hasInvites = !lastInvite.HasValue || inviteCount > 0;
    var canInvite = hasInvites && weekSinceLastInvite;
    
    if(!canInvite)
    {
        return;
    }
    
    0 讨论(0)
提交回复
热议问题