How do I use DateTime.TryParse with a Nullable?

前端 未结 9 493
逝去的感伤
逝去的感伤 2020-12-02 15:06

I want to use the DateTime.TryParse method to get the datetime value of a string into a Nullable. But when I try this:

DateTime? d;
bool success = DateTime.         


        
相关标签:
9条回答
  • 2020-12-02 15:34

    Here's a single line solution:

    DateTime? d = DateTime.TryParse("text", out DateTime parseDate) ? parseDate : (DateTime?)null;
    
    0 讨论(0)
  • 2020-12-02 15:45

    Alternatively, if you are not concerned with the possible exception raised, you could change TryParse for Parse:

    DateTime? d = DateTime.Parse("some valid text");
    

    Although there won't be a boolean indicating success either, it could be practical in some situations where you know that the input text will always be valid.

    0 讨论(0)
  • 2020-12-02 15:48

    What about creating an extension method?

    public static class NullableExtensions
    {
        public static bool TryParse(this DateTime? dateTime, string dateString, out DateTime? result)
        {
            DateTime tempDate;
            if(! DateTime.TryParse(dateString,out tempDate))
            {
                result = null;
                return false;
            }
    
            result = tempDate;
            return true;
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题