Set an empty DateTime variable

前端 未结 12 2029
走了就别回头了
走了就别回头了 2020-12-16 08:59

I would declare an empty String variable like this:

    string myString = string.Empty;

Is there an equivalent for a \'DateTime\' variable

相关标签:
12条回答
  • 2020-12-16 09:23

    Option 1: Use a nullable DateTime?

    Option 2: Use DateTime.MinValue

    Personally, I'd prefer option 1.

    0 讨论(0)
  • 2020-12-16 09:25

    There's no such thing as an empty date per se, do you mean something like:

    DateTime? myDateTime = null;
    
    0 讨论(0)
  • 2020-12-16 09:28

    You may want to use a nullable datetime. Datetime? someDate = null;

    You may find instances of people using DateTime.Max or DateTime.Min in such instances, but I highly doubt you want to do that. It leads to bugs with edge cases, code that's harder to read, etc.

    0 讨论(0)
  • 2020-12-16 09:30

    Either:

    DateTime dt = new DateTime();
    

    or

    DateTime dt = default(DateTime);
    
    0 讨论(0)
  • 2020-12-16 09:32

    This will work for null able dateTime parameter

    . .

    SearchUsingDate(DateTime? StartDate, DateTime? EndDate){
         DateTime LastDate;
         if (EndDate != null)
           {
              LastDate = (DateTime)EndDate;
              LastDate = LastDate.AddDays(1);
              EndDate = LastDate;
            }
    }
    
    0 讨论(0)
  • 2020-12-16 09:37

    No. You have 2 options:

    DateTime date = DateTime.MinValue;
    

    This works when you need to do something every X amount of time (since you will always be over MinValue) but can actually cause subtle errors (such as using some operators w/o first checking if you are not MinValue) if you are not careful.

    And you can use Nullable:

    DateTime? date = null;
    

    Which is nice and avoids most issues while introducing only 1 or 2.

    It really depends on what you are trying to achieve.

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