none
Comparing Two DateTime RRS feed

  • Question

  • Greetings,

    I'm trying to compare a DateTime.Now with another get,set DateTime.Now

    public DateTime? StatusUntil
    {
    get;
    set;
    }


    if (StatusUntil == DateTime.Now) // this line is not right { Console.WriteLine("Time remains is " + remainingminutes); // so as "remainingminutes" thing }

    I want to get the remaining minutes of the "StatusUntil" until DateTime.Now by comparing it
    lets say: (an explanation)
    if StatusUntil = 2018-01-01 16:00:00 and DateTime.Now equals 2018-01-01 15:45:00

    then it gives the remainingminutes "15",  and only in a range from 60 to 11 minutes, else, nothing.
    hope you understand ..

    Any help please?

    Sunday, February 25, 2018 11:32 PM

Answers

  • You have to do things a little differently when you're using a Nullable DateTime. This should work for you:

    DateTime now = DateTime.Now;
    if (StatusUntil.HasValue && (StatusUntil > now))
    {
        var remainingminutes = (StatusUntil - now).Value.Minutes;
        Console.WriteLine("Time remains is " + remainingminutes); 
    }
    


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    • Proposed as answer by Hart Wang Monday, February 26, 2018 6:18 AM
    • Marked as answer by Zuher Laith Thursday, March 1, 2018 2:03 PM
    Monday, February 26, 2018 1:14 AM
    Moderator

All replies

  • You have to do things a little differently when you're using a Nullable DateTime. This should work for you:

    DateTime now = DateTime.Now;
    if (StatusUntil.HasValue && (StatusUntil > now))
    {
        var remainingminutes = (StatusUntil - now).Value.Minutes;
        Console.WriteLine("Time remains is " + remainingminutes); 
    }
    


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    • Proposed as answer by Hart Wang Monday, February 26, 2018 6:18 AM
    • Marked as answer by Zuher Laith Thursday, March 1, 2018 2:03 PM
    Monday, February 26, 2018 1:14 AM
    Moderator
  • You have to do things a little differently when you're using a Nullable DateTime. This should work for you:

    DateTime now = DateTime.Now;
    if (StatusUntil.HasValue && (StatusUntil > now))
    {
        var remainingminutes = (StatusUntil - now).Value.Minutes;
        Console.WriteLine("Time remains is " + remainingminutes); 
    }

    Perfect Answer!,
    but may I ask, why using HasValue instead of null in DateTime Structure?

    Best Regards.

    Thursday, March 1, 2018 2:06 PM
  • Perfect Answer!,
    but may I ask, why using HasValue instead of null in DateTime Structure?


    I have no idea! I suppose it was a design decision by the C# team when they added those Nullable types.

    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Thursday, March 1, 2018 3:05 PM
    Moderator